import { scrollViewWebProps } from '@/lib/ui/scroll-props';
import {
  StyleSheet,
  Text,
  View,
  ScrollView,
  ActivityIndicator,
  TouchableOpacity,
  Share,
  Platform,
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { Stack } from "expo-router";
import { Receipt, Download, Tag, CheckCircle2 } from "lucide-react-native";

import Colors from "@/constants/colors";
import { trpc } from "@/lib/trpc";
import { useAuth } from "@/lib/auth-context";
import { showAlert } from "@/lib/utils/alert";

const QUARTER_LABELS = ["Q1 (Jan-Mar)", "Q2 (Apr-Jun)", "Q3 (Jul-Sep)", "Q4 (Oct-Dec)"];

export default function TaxSummaryScreen() {
  const insets = useSafeAreaInsets();
  const { isDemoMode } = useAuth();
  const summaryQuery = trpc.tax.summary.useQuery(undefined, { enabled: !isDemoMode });
  const categorizedQuery = trpc.tax.categorized.useQuery(undefined, { enabled: !isDemoMode });
  const exportQuery = trpc.tax.export.useQuery(undefined, { enabled: false });
  const data = summaryQuery.data;
  const categorized = categorizedQuery.data;

  const handleExport = async () => {
    try {
      const result = await exportQuery.refetch();
      const text = result.data?.text;
      if (!text) {
        showAlert("Couldn't generate export", "Try again in a moment.");
        return;
      }
      if (Platform.OS === "web") {
        showAlert("Tax summary ready", "Sharing isn't available on web. Open the app on mobile to share or save it.");
        return;
      }
      await Share.share({ message: text, title: "Zendo Tax Engine Summary" });
    } catch {
      showAlert("Couldn't export", "Something went wrong generating your summary.");
    }
  };

  return (
    <View style={[styles.container, { paddingTop: insets.top }]}>
      <Stack.Screen options={{ title: "Zendo Tax Engine", headerShown: true }} />

      {isDemoMode ? (
        <View style={styles.emptyState}>
          <Receipt size={48} color={Colors.dark.textTertiary} />
          <Text style={styles.emptyText}>The Tax Engine needs a real account with income history.</Text>
        </View>
      ) : summaryQuery.isLoading ? (
        <ActivityIndicator color={Colors.dark.primary} style={{ marginTop: 60 }} />
      ) : !data ? (
        <View style={styles.emptyState}>
          <Text style={styles.emptyText}>Couldn&apos;t load your tax summary.</Text>
        </View>
      ) : (
        <ScrollView contentContainerStyle={styles.content} showsVerticalScrollIndicator={scrollViewWebProps.showsVerticalScrollIndicator}>
          <View style={styles.heroCard}>
            <Text style={styles.heroLabel}>{data.year} income received</Text>
            <Text style={styles.heroValue}>${data.totalIncome.toFixed(2)}</Text>
            <View style={styles.heroDivider} />
            <Text style={styles.heroLabel}>Estimated set-aside ({(data.rate * 100).toFixed(0)}%)</Text>
            <Text style={styles.heroSetAside}>${data.totalEstimatedSetAside.toFixed(2)}</Text>
          </View>

          <TouchableOpacity style={styles.exportButton} onPress={handleExport} disabled={exportQuery.isFetching}>
            {exportQuery.isFetching ? (
              <ActivityIndicator color="#fff" size="small" />
            ) : (
              <>
                <Download size={16} color="#fff" />
                <Text style={styles.exportButtonText}>Export ready-to-file summary</Text>
              </>
            )}
          </TouchableOpacity>

          <Text style={styles.disclaimer}>
            This is a rough estimate based on a flat {(data.rate * 100).toFixed(0)}% self-employment
            set-aside on money you&apos;ve received - not tax advice. Talk to an accountant for your
            actual liability.
          </Text>

          <Text style={styles.sectionTitle}>By Quarter</Text>
          <View style={styles.list}>
            {data.quarters.map((q, i) => (
              <View key={q.quarter} style={styles.quarterRow}>
                <View style={styles.quarterInfo}>
                  <Text style={styles.quarterLabel}>{QUARTER_LABELS[i]}</Text>
                  <Text style={styles.quarterMeta}>{q.transactionCount} payments received</Text>
                </View>
                <View style={styles.quarterAmounts}>
                  <Text style={styles.quarterIncome}>${q.income.toFixed(2)}</Text>
                  <Text style={styles.quarterSetAside}>set aside ${q.estimatedSetAside.toFixed(2)}</Text>
                </View>
              </View>
            ))}
          </View>

          <View style={styles.sectionHeaderRow}>
            <Tag size={16} color={Colors.dark.primary} />
            <Text style={[styles.sectionTitle, { marginBottom: 0 }]}>Auto-categorized expenses</Text>
          </View>

          {categorizedQuery.isLoading ? (
            <ActivityIndicator color={Colors.dark.primary} style={{ marginTop: 20 }} />
          ) : categorized && categorized.categories.length > 0 ? (
            <>
              <View style={styles.categorySummaryRow}>
                <View style={styles.categorySummaryItem}>
                  <Text style={styles.categorySummaryValue}>${categorized.totalLikelyDeductible.toFixed(2)}</Text>
                  <Text style={styles.categorySummaryLabel}>Likely deductible</Text>
                </View>
                <View style={styles.categorySummaryItem}>
                  <Text style={styles.categorySummaryValue}>${categorized.estimatedTaxSavingsFromDeductions.toFixed(2)}</Text>
                  <Text style={styles.categorySummaryLabel}>Est. tax savings</Text>
                </View>
              </View>
              <View style={styles.list}>
                {categorized.categories.map((c) => (
                  <View key={c.category} style={styles.categoryRow}>
                    <View style={styles.categoryInfo}>
                      <View style={styles.categoryLabelRow}>
                        <Text style={styles.categoryLabel}>{c.category}</Text>
                        {c.likelyDeductible && <CheckCircle2 size={14} color={Colors.dark.success} />}
                      </View>
                      <Text style={styles.quarterMeta}>{c.transactionCount} transaction{c.transactionCount === 1 ? "" : "s"}</Text>
                    </View>
                    <Text style={styles.quarterIncome}>${c.total.toFixed(2)}</Text>
                  </View>
                ))}
              </View>
            </>
          ) : (
            <Text style={styles.emptyText}>No expense transactions with notes to categorize yet - add a note when you pay someone and it'll show up here.</Text>
          )}
        </ScrollView>
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: Colors.dark.background,
  },
  content: {
    padding: 20,
    paddingBottom: 60,
  },
  emptyState: {
    alignItems: "center" as const,
    marginTop: 80,
    gap: 12,
    paddingHorizontal: 30,
  },
  emptyText: {
    fontSize: 13,
    color: Colors.dark.textSecondary,
    textAlign: "center" as const,
    lineHeight: 18,
  },
  heroCard: {
    backgroundColor: Colors.dark.surface,
    borderRadius: 18,
    borderWidth: 1,
    borderColor: Colors.dark.border,
    padding: 24,
    alignItems: "center" as const,
  },
  heroLabel: {
    fontSize: 12,
    color: Colors.dark.textSecondary,
    textTransform: "uppercase" as const,
  },
  heroValue: {
    fontSize: 32,
    fontWeight: "800" as const,
    color: Colors.dark.text,
    marginTop: 4,
  },
  heroDivider: {
    height: 1,
    width: "60%",
    backgroundColor: Colors.dark.border,
    marginVertical: 16,
  },
  heroSetAside: {
    fontSize: 24,
    fontWeight: "800" as const,
    color: Colors.dark.warning,
    marginTop: 4,
  },
  exportButton: {
    flexDirection: "row" as const,
    alignItems: "center" as const,
    justifyContent: "center" as const,
    gap: 8,
    backgroundColor: Colors.dark.primary,
    borderRadius: 14,
    paddingVertical: 14,
    marginTop: 14,
  },
  exportButtonText: {
    fontSize: 14,
    fontWeight: "700" as const,
    color: "#fff",
  },
  disclaimer: {
    fontSize: 12,
    color: Colors.dark.textTertiary,
    lineHeight: 17,
    marginTop: 16,
    marginBottom: 24,
  },
  sectionTitle: {
    fontSize: 16,
    fontWeight: "700" as const,
    color: Colors.dark.text,
    marginBottom: 12,
  },
  sectionHeaderRow: {
    flexDirection: "row" as const,
    alignItems: "center" as const,
    gap: 7,
    marginTop: 28,
    marginBottom: 12,
  },
  list: {
    gap: 10,
  },
  quarterRow: {
    flexDirection: "row" as const,
    justifyContent: "space-between" as const,
    alignItems: "center" as const,
    backgroundColor: Colors.dark.surface,
    borderRadius: 14,
    borderWidth: 1,
    borderColor: Colors.dark.border,
    padding: 14,
  },
  quarterInfo: {
    flex: 1,
  },
  quarterLabel: {
    fontSize: 14,
    fontWeight: "700" as const,
    color: Colors.dark.text,
  },
  quarterMeta: {
    fontSize: 12,
    color: Colors.dark.textTertiary,
    marginTop: 2,
  },
  quarterAmounts: {
    alignItems: "flex-end" as const,
  },
  quarterIncome: {
    fontSize: 15,
    fontWeight: "700" as const,
    color: Colors.dark.text,
  },
  quarterSetAside: {
    fontSize: 11,
    color: Colors.dark.warning,
    marginTop: 2,
  },
  categorySummaryRow: {
    flexDirection: "row" as const,
    gap: 12,
    marginBottom: 14,
  },
  categorySummaryItem: {
    flex: 1,
    backgroundColor: Colors.dark.surface,
    borderRadius: 14,
    borderWidth: 1,
    borderColor: Colors.dark.border,
    padding: 14,
    alignItems: "center" as const,
  },
  categorySummaryValue: {
    fontSize: 18,
    fontWeight: "800" as const,
    color: Colors.dark.success,
  },
  categorySummaryLabel: {
    fontSize: 11,
    color: Colors.dark.textSecondary,
    marginTop: 2,
    textAlign: "center" as const,
  },
  categoryRow: {
    flexDirection: "row" as const,
    justifyContent: "space-between" as const,
    alignItems: "center" as const,
    backgroundColor: Colors.dark.surface,
    borderRadius: 14,
    borderWidth: 1,
    borderColor: Colors.dark.border,
    padding: 14,
  },
  categoryInfo: {
    flex: 1,
  },
  categoryLabelRow: {
    flexDirection: "row" as const,
    alignItems: "center" as const,
    gap: 6,
  },
  categoryLabel: {
    fontSize: 14,
    fontWeight: "700" as const,
    color: Colors.dark.text,
  },
});
