import { scrollViewWebProps } from '@/lib/ui/scroll-props';
import {
  Text,
  View,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  ActivityIndicator,
  Dimensions,
} from "react-native";
import { Stack, useRouter } from "expo-router";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import Colors from "@/constants/colors";
import { trpc } from "@/lib/trpc";
import { useState } from "react";
import {
  ChevronLeft,
  DollarSign,
  BarChart3,
  PieChart,
  ArrowUpRight,
  ArrowDownRight,
} from "lucide-react-native";

const { width } = Dimensions.get("window");

type Period = "week" | "month" | "year";

export default function AnalyticsScreen() {
  const insets = useSafeAreaInsets();
  const router = useRouter();
  const [period, setPeriod] = useState<Period>("month");

  const dashboardQuery = trpc.analytics.dashboard.useQuery({ period });
  const spendingQuery = trpc.analytics.spending.useQuery();

  const data = dashboardQuery.data;
  const spending = spendingQuery.data;

  const formatMoney = (amount: number) => {
    return `$${amount.toFixed(2)}`;
  };

  const renderMiniChart = (chartData: { date: string; sent: number; received: number }[]) => {
    if (!chartData || chartData.length === 0) return null;

    const maxValue = Math.max(
      ...chartData.map((d) => Math.max(d.sent, d.received))
    );

    const chartWidth = width - 80;
    const chartHeight = 60;
    const pointWidth = chartWidth / (chartData.length - 1 || 1);

    const sentPath: { x: number; y: number }[] = chartData.map((d, i) => ({
      x: i * pointWidth,
      y: chartHeight - (d.sent / maxValue) * chartHeight,
    }));

    const receivedPath: { x: number; y: number }[] = chartData.map((d, i) => ({
      x: i * pointWidth,
      y: chartHeight - (d.received / maxValue) * chartHeight,
    }));

    return (
      <View style={styles.miniChartContainer}>
        {sentPath.map((point, i) => {
          if (i === 0) return null;
          const prevPoint = sentPath[i - 1];
          return (
            <View
              key={`sent-${i}`}
              style={[
                styles.chartLine,
                {
                  position: "absolute" as const,
                  left: prevPoint.x,
                  top: prevPoint.y,
                  width: Math.sqrt(
                    Math.pow(point.x - prevPoint.x, 2) + Math.pow(point.y - prevPoint.y, 2)
                  ),
                  transform: [
                    {
                      rotate: `${Math.atan2(point.y - prevPoint.y, point.x - prevPoint.x)}rad`,
                    },
                  ],
                  backgroundColor: Colors.dark.error,
                },
              ]}
            />
          );
        })}
        {receivedPath.map((point, i) => {
          if (i === 0) return null;
          const prevPoint = receivedPath[i - 1];
          return (
            <View
              key={`received-${i}`}
              style={[
                styles.chartLine,
                {
                  position: "absolute" as const,
                  left: prevPoint.x,
                  top: prevPoint.y,
                  width: Math.sqrt(
                    Math.pow(point.x - prevPoint.x, 2) + Math.pow(point.y - prevPoint.y, 2)
                  ),
                  transform: [
                    {
                      rotate: `${Math.atan2(point.y - prevPoint.y, point.x - prevPoint.x)}rad`,
                    },
                  ],
                  backgroundColor: Colors.dark.success,
                },
              ]}
            />
          );
        })}
      </View>
    );
  };

  return (
    <View style={[styles.container, { paddingTop: insets.top }]}>
      <Stack.Screen
        options={{
          headerShown: false,
        }}
      />

      <View style={styles.header}>
        <TouchableOpacity
          onPress={() => router.back()}
          hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}
        >
          <ChevronLeft color={Colors.dark.text} size={24} />
        </TouchableOpacity>
        <Text style={styles.headerTitle}>Analytics</Text>
        <View style={{ width: 24 }} />
      </View>

      <View style={styles.periodSelector}>
        {(["week", "month", "year"] as Period[]).map((p) => (
          <TouchableOpacity
            key={p}
            style={[
              styles.periodButton,
              period === p && styles.periodButtonActive,
            ]}
            onPress={() => setPeriod(p)}
          >
            <Text
              style={[
                styles.periodButtonText,
                period === p && styles.periodButtonTextActive,
              ]}
            >
              {p.charAt(0).toUpperCase() + p.slice(1)}
            </Text>
          </TouchableOpacity>
        ))}
      </View>

      {dashboardQuery.isLoading ? (
        <View style={styles.loadingContainer}>
          <ActivityIndicator size="large" color={Colors.dark.tint} />
        </View>
      ) : (
        <ScrollView
          style={styles.scrollView}
          contentContainerStyle={styles.content}
          showsVerticalScrollIndicator={scrollViewWebProps.showsVerticalScrollIndicator}
        >
          <View style={styles.summaryCards}>
            <View style={styles.summaryCard}>
              <View
                style={[
                  styles.summaryIcon,
                  { backgroundColor: `${Colors.dark.error}20` },
                ]}
              >
                <ArrowUpRight size={20} color={Colors.dark.error} />
              </View>
              <Text style={styles.summaryLabel}>Total Sent</Text>
              <Text style={styles.summaryValue}>
                {formatMoney(data?.summary.totalSent || 0)}
              </Text>
            </View>

            <View style={styles.summaryCard}>
              <View
                style={[
                  styles.summaryIcon,
                  { backgroundColor: `${Colors.dark.success}20` },
                ]}
              >
                <ArrowDownRight size={20} color={Colors.dark.success} />
              </View>
              <Text style={styles.summaryLabel}>Total Received</Text>
              <Text style={styles.summaryValue}>
                {formatMoney(data?.summary.totalReceived || 0)}
              </Text>
            </View>
          </View>

          <View style={styles.summaryCards}>
            <View style={styles.summaryCard}>
              <View
                style={[
                  styles.summaryIcon,
                  { backgroundColor: `${Colors.dark.tint}20` },
                ]}
              >
                <DollarSign size={20} color={Colors.dark.tint} />
              </View>
              <Text style={styles.summaryLabel}>Current Balance</Text>
              <Text style={styles.summaryValue}>
                {formatMoney(data?.summary.currentBalance || 0)}
              </Text>
            </View>

            <View style={styles.summaryCard}>
              <View
                style={[
                  styles.summaryIcon,
                  { backgroundColor: `${Colors.dark.textSecondary}20` },
                ]}
              >
                <BarChart3 size={20} color={Colors.dark.textSecondary} />
              </View>
              <Text style={styles.summaryLabel}>Transactions</Text>
              <Text style={styles.summaryValue}>
                {data?.summary.transactionCount || 0}
              </Text>
            </View>
          </View>

          <View style={styles.chartCard}>
            <Text style={styles.chartTitle}>Transaction Activity</Text>
            <View style={styles.chartLegend}>
              <View style={styles.legendItem}>
                <View
                  style={[
                    styles.legendDot,
                    { backgroundColor: Colors.dark.error },
                  ]}
                />
                <Text style={styles.legendText}>Sent</Text>
              </View>
              <View style={styles.legendItem}>
                <View
                  style={[
                    styles.legendDot,
                    { backgroundColor: Colors.dark.success },
                  ]}
                />
                <Text style={styles.legendText}>Received</Text>
              </View>
            </View>
            {data && data.chartData.length > 0 ? (
              renderMiniChart(data.chartData)
            ) : (
              <View style={styles.noDataContainer}>
                <Text style={styles.noDataText}>No transaction data</Text>
              </View>
            )}
          </View>

          {data && data.topRecipients.length > 0 && (
            <View style={styles.section}>
              <Text style={styles.sectionTitle}>Top Recipients</Text>
              {data.topRecipients.map((recipient, index) => (
                <View key={recipient.userId} style={styles.recipientCard}>
                  <View style={styles.recipientRank}>
                    <Text style={styles.recipientRankText}>{index + 1}</Text>
                  </View>
                  <View style={styles.recipientInfo}>
                    <Text style={styles.recipientName}>
                      {recipient.displayName}
                    </Text>
                    <Text style={styles.recipientUsername}>
                      @{recipient.username}
                    </Text>
                  </View>
                  <Text style={styles.recipientAmount}>
                    {formatMoney(recipient.amountSent)}
                  </Text>
                </View>
              ))}
            </View>
          )}

          {spending && Object.keys(spending.spendingByCategory).length > 0 && (
            <View style={styles.section}>
              <Text style={styles.sectionTitle}>Spending by Category</Text>
              {Object.entries(spending.spendingByCategory).map(([category, amount]) => {
                const percentage =
                  (amount / spending.totalSpent) * 100 || 0;
                return (
                  <View key={category} style={styles.categoryCard}>
                    <View style={styles.categoryInfo}>
                      <Text style={styles.categoryName}>{category}</Text>
                      <Text style={styles.categoryAmount}>
                        {formatMoney(amount)}
                      </Text>
                    </View>
                    <View style={styles.progressBar}>
                      <View
                        style={[
                          styles.progressFill,
                          {
                            width: `${Math.min(percentage, 100)}%`,
                            backgroundColor: Colors.dark.tint,
                          },
                        ]}
                      />
                    </View>
                    <Text style={styles.categoryPercentage}>
                      {percentage.toFixed(1)}%
                    </Text>
                  </View>
                );
              })}
            </View>
          )}

          <View style={styles.insightCard}>
            <View style={styles.insightIcon}>
              <PieChart size={24} color={Colors.dark.tint} />
            </View>
            <View style={styles.insightContent}>
              <Text style={styles.insightTitle}>Transaction Insights</Text>
              <Text style={styles.insightText}>
                {data?.summary.totalReceived &&
                data.summary.totalSent &&
                data.summary.totalReceived > data.summary.totalSent
                  ? `You received ${formatMoney(data.summary.totalReceived - data.summary.totalSent)} more than you sent this ${period}`
                  : data?.summary.totalSent && data.summary.totalReceived
                  ? `You sent ${formatMoney(data.summary.totalSent - data.summary.totalReceived)} more than you received this ${period}`
                  : "Start making transactions to see insights"}
              </Text>
            </View>
          </View>
        </ScrollView>
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: Colors.dark.background,
  },
  header: {
    flexDirection: "row" as const,
    alignItems: "center" as const,
    justifyContent: "space-between" as const,
    paddingHorizontal: 20,
    paddingVertical: 16,
    borderBottomWidth: 1,
    borderBottomColor: Colors.dark.border,
  },
  headerTitle: {
    fontSize: 20,
    fontWeight: "700" as const,
    color: Colors.dark.text,
  },
  periodSelector: {
    flexDirection: "row" as const,
    padding: 20,
    gap: 12,
  },
  periodButton: {
    flex: 1,
    paddingVertical: 10,
    borderRadius: 12,
    backgroundColor: Colors.dark.surface,
    alignItems: "center" as const,
    borderWidth: 1,
    borderColor: Colors.dark.border,
  },
  periodButtonActive: {
    backgroundColor: Colors.dark.tint,
    borderColor: Colors.dark.tint,
  },
  periodButtonText: {
    fontSize: 14,
    fontWeight: "600" as const,
    color: Colors.dark.textSecondary,
  },
  periodButtonTextActive: {
    color: Colors.dark.text,
  },
  loadingContainer: {
    flex: 1,
    justifyContent: "center" as const,
    alignItems: "center" as const,
  },
  scrollView: {
    flex: 1,
  },
  content: {
    padding: 20,
    gap: 20,
  },
  summaryCards: {
    flexDirection: "row" as const,
    gap: 12,
  },
  summaryCard: {
    flex: 1,
    backgroundColor: Colors.dark.card,
    borderRadius: 16,
    padding: 16,
  },
  summaryIcon: {
    width: 40,
    height: 40,
    borderRadius: 20,
    justifyContent: "center" as const,
    alignItems: "center" as const,
    marginBottom: 12,
  },
  summaryLabel: {
    fontSize: 12,
    color: Colors.dark.textSecondary,
    marginBottom: 4,
  },
  summaryValue: {
    fontSize: 20,
    fontWeight: "700" as const,
    color: Colors.dark.text,
  },
  chartCard: {
    backgroundColor: Colors.dark.card,
    borderRadius: 16,
    padding: 20,
  },
  chartTitle: {
    fontSize: 18,
    fontWeight: "700" as const,
    color: Colors.dark.text,
    marginBottom: 16,
  },
  chartLegend: {
    flexDirection: "row" as const,
    gap: 20,
    marginBottom: 20,
  },
  legendItem: {
    flexDirection: "row" as const,
    alignItems: "center" as const,
    gap: 8,
  },
  legendDot: {
    width: 12,
    height: 12,
    borderRadius: 6,
  },
  legendText: {
    fontSize: 12,
    color: Colors.dark.textSecondary,
  },
  miniChartContainer: {
    height: 60,
    position: "relative" as const,
    marginTop: 10,
  },
  chartLine: {
    height: 2,
  },
  noDataContainer: {
    height: 60,
    justifyContent: "center" as const,
    alignItems: "center" as const,
  },
  noDataText: {
    fontSize: 14,
    color: Colors.dark.textSecondary,
  },
  section: {
    gap: 12,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: "700" as const,
    color: Colors.dark.text,
    marginBottom: 4,
  },
  recipientCard: {
    flexDirection: "row" as const,
    alignItems: "center" as const,
    backgroundColor: Colors.dark.card,
    borderRadius: 12,
    padding: 16,
    gap: 12,
  },
  recipientRank: {
    width: 32,
    height: 32,
    borderRadius: 16,
    backgroundColor: Colors.dark.tint,
    justifyContent: "center" as const,
    alignItems: "center" as const,
  },
  recipientRankText: {
    fontSize: 14,
    fontWeight: "700" as const,
    color: Colors.dark.text,
  },
  recipientInfo: {
    flex: 1,
  },
  recipientName: {
    fontSize: 14,
    fontWeight: "600" as const,
    color: Colors.dark.text,
  },
  recipientUsername: {
    fontSize: 12,
    color: Colors.dark.textSecondary,
  },
  recipientAmount: {
    fontSize: 16,
    fontWeight: "700" as const,
    color: Colors.dark.text,
  },
  categoryCard: {
    backgroundColor: Colors.dark.card,
    borderRadius: 12,
    padding: 16,
    gap: 8,
  },
  categoryInfo: {
    flexDirection: "row" as const,
    justifyContent: "space-between" as const,
    alignItems: "center" as const,
  },
  categoryName: {
    fontSize: 14,
    fontWeight: "600" as const,
    color: Colors.dark.text,
  },
  categoryAmount: {
    fontSize: 14,
    fontWeight: "600" as const,
    color: Colors.dark.textSecondary,
  },
  progressBar: {
    height: 6,
    backgroundColor: Colors.dark.background,
    borderRadius: 3,
    overflow: "hidden" as const,
  },
  progressFill: {
    height: "100%",
    borderRadius: 3,
  },
  categoryPercentage: {
    fontSize: 12,
    color: Colors.dark.textSecondary,
    alignSelf: "flex-end" as const,
  },
  insightCard: {
    flexDirection: "row" as const,
    backgroundColor: Colors.dark.card,
    borderRadius: 16,
    padding: 20,
    gap: 16,
  },
  insightIcon: {
    width: 48,
    height: 48,
    borderRadius: 24,
    backgroundColor: `${Colors.dark.tint}20`,
    justifyContent: "center" as const,
    alignItems: "center" as const,
  },
  insightContent: {
    flex: 1,
  },
  insightTitle: {
    fontSize: 16,
    fontWeight: "700" as const,
    color: Colors.dark.text,
    marginBottom: 4,
  },
  insightText: {
    fontSize: 14,
    color: Colors.dark.textSecondary,
    lineHeight: 20,
  },
});
