import React, { useEffect, useMemo, useState } from 'react';
import {
  View,
  Text,
  ScrollView,
  RefreshControl,
  StyleSheet,
  TouchableOpacity,
} from 'react-native';
import { useSelector, useDispatch } from 'react-redux';
import { useNavigation } from '@react-navigation/native';
import type { AppDispatch } from '@/store/store';
import Icon from 'react-native-vector-icons/MaterialIcons';
import { Container, LoadingSpinner, ErrorState } from '@/shared/components/ui';
import { useTheme } from '@/shared/styles/useTheme';
import { fetchZohoBooksData } from '../store/zohoBooksSlice';
import {
  selectZohoBooksLoading,
  selectZohoBooksError,
  selectZohoBooksKPIData,
  selectCustomers,
  selectVendors,
  selectActiveInvoices,
  selectPaidInvoices,
  selectDraftInvoices,
  selectTopCustomersByOutstanding,
  selectTopVendorsByOutstanding,
  selectInvoiceStatusDistribution,
} from '../store/selectors';
import {
  KPIWidget,
  RevenueChart,
  BarChartWidget,
  ListWidget,
} from '../components/widgets';

const ZohoBooksDashboardScreen: React.FC = () => {
  const { colors, fonts, spacing, shadows } = useTheme();
  const navigation = useNavigation();
  const [refreshing, setRefreshing] = useState(false);

  // Redux
  const dispatch = useDispatch<AppDispatch>();
  const loading = useSelector(selectZohoBooksLoading);
  const error = useSelector(selectZohoBooksError);
  const kpiData = useSelector(selectZohoBooksKPIData);
  const customers = useSelector(selectCustomers);
  const vendors = useSelector(selectVendors);
  const activeInvoices = useSelector(selectActiveInvoices);
  const paidInvoices = useSelector(selectPaidInvoices);
  const draftInvoices = useSelector(selectDraftInvoices);
  const topCustomers = useSelector(selectTopCustomersByOutstanding);
  const topVendors = useSelector(selectTopVendorsByOutstanding);
  const invoiceStatusDistribution = useSelector(selectInvoiceStatusDistribution);

  // Effects
  useEffect(() => {
    dispatch(fetchZohoBooksData());
  }, [dispatch]);

  // Handlers
  const handleRefresh = async () => {
    setRefreshing(true);
    try {
      await dispatch(fetchZohoBooksData()).unwrap();
    } catch (error) {
      console.error('Error refreshing data:', error);
    } finally {
      setRefreshing(false);
    }
  };

  const handleRetry = () => {
    dispatch(fetchZohoBooksData());
  };

  // Computed data for charts
  const invoiceStatusData = useMemo(() => {
    return invoiceStatusDistribution.map(item => ({
      label: item.label,
      value: item.value,
      color: item.color,
    }));
  }, [invoiceStatusDistribution]);

  const customerVsVendorData = useMemo(() => {
    return [
      { label: 'Customers', value: kpiData.totalCustomers, color: colors.chartPrimary },
      { label: 'Vendors', value: kpiData.totalVendors, color: colors.chartSecondary },
    ];
  }, [kpiData.totalCustomers, kpiData.totalVendors, colors]);

  const revenueVsExpensesData = useMemo(() => {
    return [
      { label: 'Revenue', value: Math.round(kpiData.totalRevenue / 1000), color: colors.success },
      { label: 'Expenses', value: Math.round(kpiData.totalExpensesAmount / 1000), color: colors.error },
    ];
  }, [kpiData.totalRevenue, kpiData.totalExpensesAmount, colors]);

  // Top customers list data
  const topCustomersListData = useMemo(() => {
    return topCustomers.map(customer => ({
      id: customer.contact_id,
      title: customer.contact_name,
      subtitle: customer.company_name || 'Individual',
      value: `₹${customer.outstanding_receivable_amount.toLocaleString()}`,
      icon: 'person',
      color: colors.primary,
    }));
  }, [topCustomers, colors]);

  // Top vendors list data
  const topVendorsListData = useMemo(() => {
    return topVendors.map(vendor => ({
      id: vendor.contact_id,
      title: vendor.contact_name,
      subtitle: vendor.company_name || 'Individual',
      value: `₹${vendor.outstanding_payable_amount.toLocaleString()}`,
      icon: 'business',
      color: colors.secondary,
    }));
  }, [topVendors, colors]);

  // Loading state
  if (loading && !kpiData.totalCustomers && !kpiData.totalVendors) {
    return <LoadingSpinner />;
  }

  // Error state
  if (error) {
    return <ErrorState onRetry={handleRetry} />;
  }

  return (
    <Container>
      <ScrollView
        style={[styles.container, { backgroundColor: colors.background }]}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={handleRefresh} />
        }
        showsVerticalScrollIndicator={false}
      >
        {/* Header */}
        <View style={styles.header}>
          <View style={styles.headerContent}>
            <Icon name="account-balance-wallet" size={28} color={colors.primary} />
            <Text style={[styles.title, { color: colors.text, fontFamily: fonts.bold }]}>
              Zoho Books Dashboard
            </Text>
          </View>
          <TouchableOpacity 
            style={styles.dataButton}
            onPress={() => navigation.navigate('ZohoBooksData' as never)}
          >
            <Icon name="list" size={20} color={colors.primary} />
            <Text style={[styles.dataButtonText, { color: colors.primary, fontFamily: fonts.medium }]}>
              View Data
            </Text>
          </TouchableOpacity>
        </View>

        {/* KPI Cards Row 1 */}
        <View style={styles.kpiRow}>
          <View style={styles.kpiColumn}>
            <KPIWidget
              title="Total Customers"
              value={kpiData.totalCustomers}
              icon="people"
              color={colors.primary}
            />
          </View>
          <View style={styles.kpiColumn}>
            <KPIWidget
              title="Total Vendors"
              value={kpiData.totalVendors}
              icon="business"
              color={colors.secondary}
            />
          </View>
        </View>

        {/* KPI Cards Row 2 */}
        <View style={styles.kpiRow}>
          <View style={styles.kpiColumn}>
            <KPIWidget
              title="Outstanding Receivables"
              value={`₹${kpiData.outstandingReceivables.toLocaleString()}`}
              icon="trending-up"
              color={colors.success}
            />
          </View>
          <View style={styles.kpiColumn}>
            <KPIWidget
              title="Outstanding Payables"
              value={`₹${kpiData.outstandingPayables.toLocaleString()}`}
              icon="trending-down"
              color={colors.error}
            />
          </View>
        </View>

        {/* KPI Cards Row 3 */}
        <View style={styles.kpiRow}>
          <View style={styles.kpiColumn}>
            <KPIWidget
              title="Total Revenue"
              value={`₹${kpiData.totalRevenue.toLocaleString()}`}
              icon="attach-money"
              color={colors.chartTertiary}
            />
          </View>
          <View style={styles.kpiColumn}>
            <KPIWidget
              title="Total Expenses"
              value={`₹${kpiData.totalExpensesAmount.toLocaleString()}`}
              icon="receipt"
              color={colors.warning}
            />
          </View>
        </View>

        {/* Charts Row */}
        <View style={styles.chartsRow}>
          <View style={styles.chartColumn}>
            <RevenueChart
              title="Invoice Status"
              data={invoiceStatusData}
              chartType="donut"
            />
          </View>
          <View style={styles.chartColumn}>
            <RevenueChart
              title="Customers vs Vendors"
              data={customerVsVendorData}
              chartType="pie"
            />
          </View>
        </View>

        {/* Bar Chart */}
        <BarChartWidget
          title="Revenue vs Expenses"
          subtitle="Amount in thousands"
          data={revenueVsExpensesData}
        />

        {/* Lists Row */}
        <View style={styles.listsRow}>
          <View style={styles.listColumn}>
            <ListWidget
              title="Top Customers"
              data={topCustomersListData}
              maxItems={4}
              emptyMessage="No customer data available"
            />
          </View>
          <View style={styles.listColumn}>
            <ListWidget
              title="Top Vendors"
              data={topVendorsListData}
              maxItems={4}
              emptyMessage="No vendor data available"
            />
          </View>
        </View>

        {/* Summary Cards */}
        <View style={styles.summaryRow}>
          <View style={[styles.summaryCard, { backgroundColor: colors.surface, borderColor: colors.border }]}>
            <View style={styles.summaryHeader}>
              <Icon name="description" size={20} color={colors.primary} />
              <Text style={[styles.summaryTitle, { color: colors.text, fontFamily: fonts.medium }]}>
                Documents
              </Text>
            </View>
            <View style={styles.summaryContent}>
              <View style={styles.summaryItem}>
                <Text style={[styles.summaryLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>
                  Invoices
                </Text>
                <Text style={[styles.summaryValue, { color: colors.text, fontFamily: fonts.bold }]}>
                  {kpiData.totalInvoices}
                </Text>
              </View>
              <View style={styles.summaryItem}>
                <Text style={[styles.summaryLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>
                  Sales Orders
                </Text>
                <Text style={[styles.summaryValue, { color: colors.text, fontFamily: fonts.bold }]}>
                  {kpiData.totalSalesOrders}
                </Text>
              </View>
              <View style={styles.summaryItem}>
                <Text style={[styles.summaryLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>
                  Purchase Orders
                </Text>
                <Text style={[styles.summaryValue, { color: colors.text, fontFamily: fonts.bold }]}>
                  {kpiData.totalPurchaseOrders}
                </Text>
              </View>
              <View style={styles.summaryItem}>
                <Text style={[styles.summaryLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>
                  Bills
                </Text>
                <Text style={[styles.summaryValue, { color: colors.text, fontFamily: fonts.bold }]}>
                  {kpiData.totalBills}
                </Text>
              </View>
            </View>
          </View>
        </View>

        {/* Bottom spacing */}
        <View style={styles.bottomSpacing} />
      </ScrollView>
    </Container>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 16,
    paddingBottom: 8,
  },
  headerContent: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  title: {
    fontSize: 24,
    marginLeft: 12,
  },
  dataButton: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 12,
    paddingVertical: 8,
    borderRadius: 8,
    backgroundColor: 'rgba(44, 95, 74, 0.1)',
    borderWidth: 1,
    borderColor: 'rgba(44, 95, 74, 0.3)',
  },
  dataButtonText: {
    fontSize: 14,
    marginLeft: 6,
  },
  kpiRow: {
    flexDirection: 'row',
    paddingHorizontal: 16,
    marginBottom: 8,
  },
  kpiColumn: {
    flex: 1,
    marginHorizontal: 4,
  },
  chartsRow: {
    flexDirection: 'column',
    paddingHorizontal: 16,
    marginBottom: 8,
  },
  chartColumn: {
    marginVertical: 4,
  },
  listsRow: {
    flexDirection: 'row',
    paddingHorizontal: 16,
    marginBottom: 8,
  },
  listColumn: {
    flex: 1,
    marginHorizontal: 4,
  },
  summaryRow: {
    paddingHorizontal: 16,
    marginBottom: 8,
  },
  summaryCard: {
    borderRadius: 12,
    borderWidth: 1,
    padding: 16,
    ...StyleSheet.flatten({
      shadowColor: '#000',
      shadowOffset: { width: 0, height: 2 },
      shadowOpacity: 0.1,
      shadowRadius: 4,
      elevation: 3,
    }),
  },
  summaryHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 16,
  },
  summaryTitle: {
    fontSize: 16,
    marginLeft: 8,
  },
  summaryContent: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-between',
  },
  summaryItem: {
    width: '48%',
    marginBottom: 12,
  },
  summaryLabel: {
    fontSize: 12,
    marginBottom: 4,
  },
  summaryValue: {
    fontSize: 18,
  },
  bottomSpacing: {
    height: 20,
  },
});

export default ZohoBooksDashboardScreen;
