import React, { useMemo } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { Container } from '@/shared/components/ui';
import { useTheme } from '@/shared/styles/useTheme';

const FinanceDashboardScreen: React.FC = () => {
  const { colors, fonts } = useTheme();

  const mock = useMemo(() => {
    // Zoho Books oriented metrics
    const cash = 246000;
    const invoices = { total: 485000, outstanding: 162000, overdue: 48000, paidThisMonth: 92000 };
    const monthlySales = [84, 92, 88, 104, 112, 118]; // in thousands
    const arAging = [45, 30, 18, 7]; // 0-30, 31-60, 61-90, 90+
    const invoiceStatus = [
      { label: 'Draft', value: 30, color: '#94A3B8' },
      { label: 'Sent', value: 80, color: '#3AA0FF' },
      { label: 'Viewed', value: 50, color: '#6366F1' },
      { label: 'Paid', value: 210, color: '#10B981' },
      { label: 'Overdue', value: 18, color: '#EF4444' },
    ];
    const taxes = { collected: 38000, paid: 12500 };
    const topCustomers = [
      { client: 'Acme Corp', amount: 82000 },
      { client: 'Initech', amount: 54000 },
      { client: 'Umbrella', amount: 48000 },
    ];
    const bankAccounts = [
      { name: 'HDFC 1234', balance: 152000 },
      { name: 'ICICI 9981', balance: 78000 },
    ];
    const paymentModes = [
      { label: 'Online', value: 120, color: '#3AA0FF' },
      { label: 'Bank Transfer', value: 90, color: '#10B981' },
      { label: 'Cash', value: 40, color: '#F59E0B' },
      { label: 'Cheque', value: 12, color: '#6366F1' },
    ];
    const estimates = { sent: 24, accepted: 16, declined: 3 };
    return { cash, invoices, monthlySales, arAging, invoiceStatus, taxes, topCustomers, bankAccounts, paymentModes, estimates };
  }, []);
  return (
    <Container>
      <View style={[styles.wrap, { backgroundColor: colors.background }]}> 
        <Text style={[styles.title, { color: colors.text, fontFamily: fonts.bold }]}>Accounts & Finance</Text>

        {/* KPIs */}
        <View style={styles.kpiGrid}>
          <Kpi label="Outstanding" value={`$${mock.invoices.outstanding.toLocaleString()}`} color={colors.text} fonts={fonts} accent="#3AA0FF" />
          <Kpi label="Overdue" value={`$${mock.invoices.overdue.toLocaleString()}`} color={colors.text} fonts={fonts} accent="#EF4444" />
          <Kpi label="Paid (This Month)" value={`$${mock.invoices.paidThisMonth.toLocaleString()}`} color={colors.text} fonts={fonts} accent="#10B981" />
          <Kpi label="Cash" value={`$${mock.cash.toLocaleString()}`} color={colors.text} fonts={fonts} accent="#6366F1" />
        </View>

        {/* Sales Trend */}
        <View style={[styles.card, { borderColor: colors.border, backgroundColor: colors.surface }]}> 
          <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Sales Trend</Text>
          <Bars data={mock.monthlySales} max={Math.max(...mock.monthlySales)} color="#3AA0FF" />
        </View>

        {/* Taxes & AR Aging */}
        <View style={styles.row}> 
          <View style={[styles.card, styles.col, { borderColor: colors.border, backgroundColor: colors.surface }]}> 
            <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Taxes</Text>
            {(() => {
              const total = Math.max(1, mock.taxes.collected + mock.taxes.paid);
              const colPct = Math.round((mock.taxes.collected / total) * 100);
              const paidPct = Math.round((mock.taxes.paid / total) * 100);
              return (
                <>
                  <Text style={{ fontSize: 12, color: colors.text, fontFamily: fonts.regular }}>Collected: ${mock.taxes.collected.toLocaleString()}</Text>
                  <Progress value={colPct} color="#10B981" fonts={fonts} />
                  <Text style={{ fontSize: 12, color: colors.text, fontFamily: fonts.regular, marginTop: 6 }}>Paid: ${mock.taxes.paid.toLocaleString()}</Text>
                  <Progress value={paidPct} color="#F59E0B" fonts={fonts} />
                </>
              );
            })()}
          </View>
          <View style={[styles.card, styles.col, { borderColor: colors.border, backgroundColor: colors.surface }]}> 
            <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>A/R Aging</Text>
            <Bars data={mock.arAging} max={Math.max(...mock.arAging)} color="#F59E0B" />
            <View style={styles.rowJustify}>
              <Text style={{ fontSize: 12, color: colors.text, fontFamily: fonts.regular }}>0-30</Text>
              <Text style={{ fontSize: 12, color: colors.text, fontFamily: fonts.regular }}>31-60</Text>
              <Text style={{ fontSize: 12, color: colors.text, fontFamily: fonts.regular }}>61-90</Text>
              <Text style={{ fontSize: 12, color: colors.text, fontFamily: fonts.regular }}>90+</Text>
            </View>
          </View>
        </View>

        {/* Invoice Status Distribution */}
        <View style={[styles.card, { borderColor: colors.border, backgroundColor: colors.surface }]}> 
          <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Invoice Status</Text>
          <Stacked segments={mock.invoiceStatus} total={mock.invoiceStatus.reduce((a, b) => a + b.value, 0)} />
          <View style={styles.legendRow}>
            {mock.invoiceStatus.map(s => (
              <View key={s.label} style={styles.legendItem}>
                <View style={[styles.legendDot, { backgroundColor: s.color }]} />
                <Text style={{ color: colors.text, fontFamily: fonts.regular }}>{s.label}</Text>
              </View>
            ))}
          </View>
        </View>

        {/* Lists */}
        <View style={styles.row}> 
          <View style={[styles.card, styles.col, { borderColor: colors.border, backgroundColor: colors.surface }]}> 
            <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Top Customers</Text>
            {mock.topCustomers.map(r => (
              <View key={r.client} style={styles.listRow}>
                <Text style={[styles.listPrimary, { color: colors.text, fontFamily: fonts.regular }]}>{r.client}</Text>
                <Text style={[styles.listSecondary, { color: colors.text, fontFamily: fonts.medium }]}>${r.amount.toLocaleString()}</Text>
              </View>
            ))}
          </View>
          <View style={[styles.card, styles.col, { borderColor: colors.border, backgroundColor: colors.surface }]}> 
            <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Bank Accounts</Text>
            {mock.bankAccounts.map(p => (
              <View key={p.name} style={styles.listRow}>
                <Text style={[styles.listPrimary, { color: colors.text, fontFamily: fonts.regular }]}>{p.name}</Text>
                <Text style={[styles.listSecondary, { color: colors.text, fontFamily: fonts.medium }]}>${p.balance.toLocaleString()}</Text>
              </View>
            ))}
          </View>
        </View>

        {/* Estimates & Payment Modes */}
        <View style={[styles.card, { borderColor: colors.border, backgroundColor: colors.surface }]}> 
          <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Estimates</Text>
          <View style={{ flexDirection: 'row', flexWrap: 'wrap' }}>
            <View style={{ paddingVertical: 6, paddingHorizontal: 10, backgroundColor: '#F3F4F6', borderRadius: 14, marginRight: 8, marginTop: 8 }}>
              <Text style={{ fontSize: 12, fontFamily: fonts.regular, color: colors.text }}>Sent: {mock.estimates.sent}</Text>
            </View>
            <View style={{ paddingVertical: 6, paddingHorizontal: 10, backgroundColor: '#E9FAF2', borderRadius: 14, marginRight: 8, marginTop: 8 }}>
              <Text style={{ fontSize: 12, fontFamily: fonts.regular, color: colors.text }}>Accepted: {mock.estimates.accepted}</Text>
            </View>
            <View style={{ paddingVertical: 6, paddingHorizontal: 10, backgroundColor: '#FFF4E6', borderRadius: 14, marginRight: 8, marginTop: 8 }}>
              <Text style={{ fontSize: 12, fontFamily: fonts.regular, color: colors.text }}>Declined: {mock.estimates.declined}</Text>
            </View>
          </View>
        </View>

        <View style={[styles.card, { borderColor: colors.border, backgroundColor: colors.surface }]}> 
          <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Payment Modes</Text>
          <Stacked segments={mock.paymentModes} total={mock.paymentModes.reduce((a, b) => a + b.value, 0)} />
          <View style={styles.legendRow}>
            {mock.paymentModes.map(s => (
              <View key={s.label} style={styles.legendItem}>
                <View style={[styles.legendDot, { backgroundColor: s.color }]} />
                <Text style={{ color: colors.text, fontFamily: fonts.regular }}>{s.label}</Text>
              </View>
            ))}
          </View>
        </View>
      </View>
    </Container>
  );
};

const styles = StyleSheet.create({
  wrap: { flex: 1, padding: 16 },
  title: { fontSize: 18, marginBottom: 8 },
  kpiGrid: { flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'space-between' },
  kpiCard: { width: '48%', borderRadius: 12, borderWidth: 1, borderColor: '#E2E8F0', backgroundColor: '#FFFFFF', padding: 12, marginBottom: 12 },
  kpiLabel: { fontSize: 12, opacity: 0.8 },
  kpiValueRow: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginTop: 8 },
  card: { borderRadius: 12, borderWidth: 1, padding: 12, marginTop: 12 },
  cardTitle: { fontSize: 16, marginBottom: 8 },
  row: { flexDirection: 'row', marginTop: 12 },
  col: { flex: 1, marginRight: 8 },
  bars: { flexDirection: 'row', alignItems: 'flex-end' },
  bar: { flex: 1, marginRight: 6, borderTopLeftRadius: 4, borderTopRightRadius: 4 },
  progressWrap: { marginTop: 8 },
  progressTrack: { height: 8, borderRadius: 6, backgroundColor: '#E5E7EB', overflow: 'hidden' },
  progressFill: { height: '100%', borderRadius: 6 },
  legendRow: { flexDirection: 'row', flexWrap: 'wrap', marginTop: 8 },
  legendItem: { flexDirection: 'row', alignItems: 'center', marginRight: 12, marginTop: 6 },
  legendDot: { width: 8, height: 8, borderRadius: 4, marginRight: 6 },
  rowJustify: { flexDirection: 'row', justifyContent: 'space-between', marginTop: 8 },
  listRow: { flexDirection: 'row', justifyContent: 'space-between', paddingVertical: 10, borderBottomWidth: StyleSheet.hairlineWidth, borderColor: '#E5E7EB' },
  listPrimary: { fontSize: 14, flex: 1, paddingRight: 8 },
  listSecondary: { fontSize: 12 },
});

export default FinanceDashboardScreen;

// UI bits
const Kpi: React.FC<{ label: string; value: string; color: string; fonts: any; accent: string }> = ({ label, value, color, fonts, accent }) => {
  return (
    <View style={styles.kpiCard}>
      <Text style={[styles.kpiLabel, { color, fontFamily: fonts.regular }]}>{label}</Text>
      <View style={styles.kpiValueRow}>
        <Text style={{ color, fontSize: 20, fontFamily: fonts.bold }}>{value}</Text>
        <View style={{ width: 10, height: 10, borderRadius: 5, backgroundColor: accent }} />
      </View>
    </View>
  );
};

const Bars: React.FC<{ data: number[]; max: number; color: string }> = ({ data, max, color }) => {
  return (
    <View style={styles.bars}>
      {data.map((v, i) => (
        <View key={i} style={[styles.bar, { height: Math.max(6, (v / Math.max(1, max)) * 64), backgroundColor: color }]} />
      ))}
    </View>
  );
};

const Progress: React.FC<{ value: number; color: string; fonts: any }> = ({ value, color, fonts }) => {
  return (
    <View style={styles.progressWrap}>
      <View style={styles.progressTrack}>
        <View style={[styles.progressFill, { width: `${value}%`, backgroundColor: color }]} />
      </View>
      <Text style={{ fontSize: 12, marginTop: 6, fontFamily: fonts.medium }}>{value}%</Text>
    </View>
  );
};

const Stacked: React.FC<{ segments: { label: string; value: number; color: string }[]; total: number }> = ({ segments, total }) => {
  return (
    <View style={{ height: 12, borderRadius: 8, backgroundColor: '#E5E7EB', overflow: 'hidden', flexDirection: 'row', marginTop: 8 }}>
      {segments.map(s => (
        <View key={s.label} style={{ width: `${(s.value / Math.max(1, total)) * 100}%`, backgroundColor: s.color }} />
      ))}
    </View>
  );
};


