import { Ionicons } from '@expo/vector-icons';
import { LinearGradient } from 'expo-linear-gradient';
import { router } from 'expo-router';
import React, { useState } from 'react';
import {
  Platform,
  ScrollView,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { useColors } from '@/hooks/useColors';
import { CREATORS, VIDEOS, formatCount } from '@/data/mockData';

const MONTHLY_DATA = [
  { month: 'Jan', amount: 42000 },
  { month: 'Feb', amount: 67500 },
  { month: 'Mar', amount: 89000 },
  { month: 'Apr', amount: 74000 },
  { month: 'May', amount: 118000 },
  { month: 'Jun', amount: 156000 },
];

const PAYOUTS = [
  { id: 'p1', date: 'Jun 1, 2026', amount: 120000, method: 'GTBank', status: 'paid' as const },
  { id: 'p2', date: 'May 1, 2026', amount: 95000, method: 'GTBank', status: 'paid' as const },
  { id: 'p3', date: 'Apr 1, 2026', amount: 68000, method: 'Opay', status: 'paid' as const },
  { id: 'p4', date: 'Mar 1, 2026', amount: 82000, method: 'GTBank', status: 'paid' as const },
];

const VIDEO_EARNINGS = [
  { videoId: 'v1', views: 284000, earnings: 68400, students: 1240 },
  { videoId: 'v2', views: 412000, earnings: 124800, students: 2180 },
  { videoId: 'v3', views: 631000, earnings: 189300, students: 3640 },
  { videoId: 'v4', views: 892000, earnings: 267600, students: 5420 },
  { videoId: 'v5', views: 198000, earnings: 59400, students: 980 },
  { videoId: 'v6', views: 346000, earnings: 103800, students: 2060 },
  { videoId: 'v7', views: 167000, earnings: 50100, students: 740 },
  { videoId: 'v8', views: 521000, earnings: 156300, students: 3120 },
];

const maxMonthly = Math.max(...MONTHLY_DATA.map((m) => m.amount));
const totalAllTime = MONTHLY_DATA.reduce((a, b) => a + b.amount, 0);
const thisMonth = MONTHLY_DATA[MONTHLY_DATA.length - 1].amount;
const available = 36000;

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

export default function EarningsScreen() {
  const colors = useColors();
  const insets = useSafeAreaInsets();
  const [period, setPeriod] = useState<Period>('month');
  const topPad = Platform.OS === 'web' ? 67 : insets.top;
  const bottomPad = Platform.OS === 'web' ? 34 : insets.bottom;

  const totalViews = VIDEO_EARNINGS.reduce((a, b) => a + b.views, 0);
  const totalStudents = VIDEO_EARNINGS.reduce((a, b) => a + b.students, 0);

  return (
    <View style={[s.screen, { backgroundColor: colors.background }]}>
      <View style={[s.header, { paddingTop: topPad + 10, borderBottomColor: colors.border }]}>
        <TouchableOpacity onPress={() => router.back()} style={s.backBtn}>
          <Ionicons name="arrow-back" size={22} color={colors.foreground} />
        </TouchableOpacity>
        <Text style={[s.headerTitle, { color: colors.foreground }]}>Earnings</Text>
        <TouchableOpacity style={s.backBtn}>
          <Ionicons name="download-outline" size={22} color={colors.foreground} />
        </TouchableOpacity>
      </View>

      <ScrollView
        showsVerticalScrollIndicator={false}
        contentContainerStyle={[s.scroll, { paddingBottom: bottomPad + 24 }]}
      >
        {/* Hero earnings card */}
        <LinearGradient
          colors={['#FF6B35', '#FF3CAC']}
          style={s.heroCard}
          start={{ x: 0, y: 0 }}
          end={{ x: 1, y: 1 }}
        >
          <View style={s.heroInner}>
            <View>
              <Text style={s.heroLabel}>This Month</Text>
              <Text style={s.heroAmount}>₦{thisMonth.toLocaleString()}</Text>
              <View style={s.heroGrowthRow}>
                <Ionicons name="trending-up" size={14} color="#fff" />
                <Text style={s.heroGrowth}> +32% vs last month</Text>
              </View>
            </View>
            <View style={s.heroDivider} />
            <View style={s.heroRight}>
              <Text style={s.heroLabel}>All Time</Text>
              <Text style={s.heroAllTime}>₦{totalAllTime.toLocaleString()}</Text>
              <Text style={s.heroLabel}>{MONTHLY_DATA.length} months</Text>
            </View>
          </View>

          <View style={[s.balanceRow]}>
            <View>
              <Text style={s.balanceLabel}>Available to Withdraw</Text>
              <Text style={s.balanceAmount}>₦{available.toLocaleString()}</Text>
            </View>
            <TouchableOpacity style={s.withdrawBtn} activeOpacity={0.85}>
              <Ionicons name="arrow-up-circle" size={16} color="#FF6B35" />
              <Text style={s.withdrawBtnText}>Withdraw</Text>
            </TouchableOpacity>
          </View>
        </LinearGradient>

        {/* Quick stats */}
        <View style={s.statsRow}>
          {[
            { label: 'Total Views', value: formatCount(totalViews), icon: 'eye-outline' },
            { label: 'Students', value: formatCount(totalStudents), icon: 'school-outline' },
            { label: 'Videos', value: `${VIDEO_EARNINGS.length}`, icon: 'videocam-outline' },
          ].map((stat) => (
            <View key={stat.label} style={[s.statCard, { backgroundColor: colors.card, borderColor: colors.border }]}>
              <View style={[s.statIcon, { backgroundColor: colors.primary + '18' }]}>
                <Ionicons name={stat.icon as any} size={18} color={colors.primary} />
              </View>
              <Text style={[s.statValue, { color: colors.foreground }]}>{stat.value}</Text>
              <Text style={[s.statLabel, { color: colors.mutedForeground }]}>{stat.label}</Text>
            </View>
          ))}
        </View>

        {/* Monthly chart */}
        <View style={[s.sectionCard, { backgroundColor: colors.card, borderColor: colors.border }]}>
          <View style={s.sectionHead}>
            <Text style={[s.sectionTitle, { color: colors.foreground }]}>Monthly Revenue</Text>
            <View style={[s.periodTabs, { backgroundColor: colors.secondary }]}>
              {(['week', 'month', 'year'] as Period[]).map((p) => (
                <TouchableOpacity
                  key={p}
                  onPress={() => setPeriod(p)}
                  style={[s.periodTab, period === p && { backgroundColor: colors.primary }]}
                >
                  <Text style={[s.periodTabText, { color: period === p ? '#fff' : colors.mutedForeground }]}>
                    {p.charAt(0).toUpperCase() + p.slice(1)}
                  </Text>
                </TouchableOpacity>
              ))}
            </View>
          </View>

          <View style={s.chart}>
            {MONTHLY_DATA.map((row, i) => {
              const pct = row.amount / maxMonthly;
              const isLast = i === MONTHLY_DATA.length - 1;
              return (
                <View key={row.month} style={s.chartCol}>
                  {isLast && (
                    <View style={[s.chartTooltip, { backgroundColor: colors.primary }]}>
                      <Text style={s.chartTooltipText}>₦{(row.amount / 1000).toFixed(0)}K</Text>
                    </View>
                  )}
                  <View style={s.barWrap}>
                    <LinearGradient
                      colors={isLast ? ['#FF6B35', '#FF3CAC'] : [colors.primary + '55', colors.primary + '22']}
                      style={[s.bar, { height: `${Math.round(pct * 100)}%` }]}
                      start={{ x: 0, y: 0 }}
                      end={{ x: 0, y: 1 }}
                    />
                  </View>
                  <Text style={[s.chartLabel, { color: colors.mutedForeground }]}>{row.month}</Text>
                </View>
              );
            })}
          </View>
        </View>

        {/* Top performing videos */}
        <Text style={[s.heading, { color: colors.foreground }]}>Top Performing Videos</Text>
        {VIDEO_EARNINGS.slice(0, 5).map((ve) => {
          const video = VIDEOS.find((v) => v.id === ve.videoId);
          if (!video) return null;
          const creator = CREATORS.find((c) => c.id === video.creatorId);
          return (
            <View key={ve.videoId} style={[s.videoRow, { backgroundColor: colors.card, borderColor: colors.border }]}>
              <LinearGradient
                colors={video.gradientColors as [string, string, string]}
                style={s.videoThumb}
                start={{ x: 0, y: 0 }}
                end={{ x: 1, y: 1 }}
              >
                <Ionicons name="play" size={18} color="rgba(255,255,255,0.8)" />
              </LinearGradient>
              <View style={s.videoMeta}>
                <Text style={[s.videoTitle, { color: colors.foreground }]} numberOfLines={2}>{video.title}</Text>
                <View style={s.videoStats}>
                  <View style={s.videoStat}>
                    <Ionicons name="eye-outline" size={12} color={colors.mutedForeground} />
                    <Text style={[s.videoStatText, { color: colors.mutedForeground }]}>{formatCount(ve.views)}</Text>
                  </View>
                  <View style={s.videoStat}>
                    <Ionicons name="school-outline" size={12} color={colors.mutedForeground} />
                    <Text style={[s.videoStatText, { color: colors.mutedForeground }]}>{formatCount(ve.students)}</Text>
                  </View>
                </View>
              </View>
              <View style={s.videoEarnings}>
                <Text style={[s.videoEarningsAmount, { color: colors.primary }]}>
                  ₦{(ve.earnings / 1000).toFixed(0)}K
                </Text>
                <Text style={[s.videoEarningsLabel, { color: colors.mutedForeground }]}>earned</Text>
              </View>
            </View>
          );
        })}

        {/* Payout history */}
        <View style={[s.sectionCard, { backgroundColor: colors.card, borderColor: colors.border, marginTop: 8 }]}>
          <View style={s.sectionHead}>
            <Text style={[s.sectionTitle, { color: colors.foreground }]}>Payout History</Text>
            <TouchableOpacity>
              <Text style={[s.seeAll, { color: colors.primary }]}>See all</Text>
            </TouchableOpacity>
          </View>
          {PAYOUTS.map((payout, idx) => (
            <View
              key={payout.id}
              style={[
                s.payoutRow,
                idx < PAYOUTS.length - 1 && { borderBottomWidth: 1, borderBottomColor: colors.border },
              ]}
            >
              <View style={[s.payoutIcon, { backgroundColor: '#22c55e18' }]}>
                <Ionicons name="checkmark-circle" size={20} color="#22c55e" />
              </View>
              <View style={s.payoutInfo}>
                <Text style={[s.payoutDate, { color: colors.foreground }]}>{payout.date}</Text>
                <Text style={[s.payoutMethod, { color: colors.mutedForeground }]}>{payout.method}</Text>
              </View>
              <View style={s.payoutRight}>
                <Text style={[s.payoutAmount, { color: colors.foreground }]}>₦{payout.amount.toLocaleString()}</Text>
                <View style={[s.payoutBadge, { backgroundColor: '#22c55e22' }]}>
                  <Text style={[s.payoutBadgeText, { color: '#22c55e' }]}>Paid</Text>
                </View>
              </View>
            </View>
          ))}
        </View>

        {/* Pending payout */}
        <View style={[s.pendingCard, { backgroundColor: colors.primary + '12', borderColor: colors.primary + '44' }]}>
          <Ionicons name="time-outline" size={20} color={colors.primary} />
          <View style={{ flex: 1 }}>
            <Text style={[s.pendingTitle, { color: colors.foreground }]}>Next Payout on Jul 1, 2026</Text>
            <Text style={[s.pendingSub, { color: colors.mutedForeground }]}>
              ₦{available.toLocaleString()} will be sent to GTBank ending ••4829
            </Text>
          </View>
          <TouchableOpacity>
            <Text style={[s.pendingChange, { color: colors.primary }]}>Change</Text>
          </TouchableOpacity>
        </View>
      </ScrollView>
    </View>
  );
}

const s = StyleSheet.create({
  screen: { flex: 1 },
  header: {
    flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between',
    paddingHorizontal: 16, paddingBottom: 14, borderBottomWidth: 1,
  },
  backBtn: { width: 36, height: 36, alignItems: 'center', justifyContent: 'center' },
  headerTitle: { fontSize: 17, fontFamily: 'Poppins_700Bold' },
  scroll: { padding: 16, gap: 12 },

  heroCard: { borderRadius: 20, overflow: 'hidden', padding: 20, gap: 16 },
  heroInner: { flexDirection: 'row', alignItems: 'flex-start', gap: 16 },
  heroLabel: { color: 'rgba(255,255,255,0.75)', fontSize: 12, fontFamily: 'Poppins_500Medium', marginBottom: 4 },
  heroAmount: { color: '#fff', fontSize: 28, fontFamily: 'Poppins_700Bold', letterSpacing: -0.5 },
  heroGrowthRow: { flexDirection: 'row', alignItems: 'center', marginTop: 4 },
  heroGrowth: { color: '#fff', fontSize: 12, fontFamily: 'Poppins_600SemiBold' },
  heroDivider: { width: 1, backgroundColor: 'rgba(255,255,255,0.25)', alignSelf: 'stretch', marginHorizontal: 4 },
  heroRight: { flex: 1 },
  heroAllTime: { color: '#fff', fontSize: 20, fontFamily: 'Poppins_700Bold', marginVertical: 2 },
  balanceRow: {
    flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between',
    backgroundColor: 'rgba(0,0,0,0.2)', borderRadius: 12, padding: 12,
  },
  balanceLabel: { color: 'rgba(255,255,255,0.75)', fontSize: 11, fontFamily: 'Poppins_500Medium', marginBottom: 2 },
  balanceAmount: { color: '#fff', fontSize: 18, fontFamily: 'Poppins_700Bold' },
  withdrawBtn: {
    flexDirection: 'row', alignItems: 'center', gap: 6,
    backgroundColor: '#fff', borderRadius: 20, paddingHorizontal: 16, paddingVertical: 9,
  },
  withdrawBtnText: { color: '#FF6B35', fontSize: 13, fontFamily: 'Poppins_700Bold' },

  statsRow: { flexDirection: 'row', gap: 10 },
  statCard: {
    flex: 1, borderRadius: 14, borderWidth: 1, padding: 12, alignItems: 'center', gap: 6,
  },
  statIcon: { width: 36, height: 36, borderRadius: 10, alignItems: 'center', justifyContent: 'center' },
  statValue: { fontSize: 16, fontFamily: 'Poppins_700Bold' },
  statLabel: { fontSize: 11, fontFamily: 'Poppins_400Regular', textAlign: 'center' },

  sectionCard: { borderRadius: 16, borderWidth: 1, padding: 16, gap: 16 },
  sectionHead: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' },
  sectionTitle: { fontSize: 15, fontFamily: 'Poppins_700Bold' },
  seeAll: { fontSize: 13, fontFamily: 'Poppins_600SemiBold' },
  periodTabs: { flexDirection: 'row', borderRadius: 8, padding: 2, gap: 2 },
  periodTab: { paddingHorizontal: 10, paddingVertical: 5, borderRadius: 6 },
  periodTabText: { fontSize: 11, fontFamily: 'Poppins_600SemiBold' },

  chart: { flexDirection: 'row', height: 120, alignItems: 'flex-end', gap: 8 },
  chartCol: { flex: 1, alignItems: 'center', gap: 4 },
  barWrap: { flex: 1, width: '100%', justifyContent: 'flex-end' },
  bar: { width: '100%', borderRadius: 4, minHeight: 4 },
  chartLabel: { fontSize: 10, fontFamily: 'Poppins_500Medium' },
  chartTooltip: {
    paddingHorizontal: 6, paddingVertical: 2, borderRadius: 4, marginBottom: 4,
  },
  chartTooltipText: { color: '#fff', fontSize: 9, fontFamily: 'Poppins_700Bold' },

  heading: { fontSize: 15, fontFamily: 'Poppins_700Bold', marginTop: 4, marginBottom: 4 },
  videoRow: {
    flexDirection: 'row', alignItems: 'center', gap: 12,
    borderRadius: 14, borderWidth: 1, padding: 12,
  },
  videoThumb: { width: 52, height: 68, borderRadius: 10, alignItems: 'center', justifyContent: 'center', flexShrink: 0 },
  videoMeta: { flex: 1 },
  videoTitle: { fontSize: 13, fontFamily: 'Poppins_600SemiBold', lineHeight: 18, marginBottom: 6 },
  videoStats: { flexDirection: 'row', gap: 12 },
  videoStat: { flexDirection: 'row', alignItems: 'center', gap: 3 },
  videoStatText: { fontSize: 11, fontFamily: 'Poppins_400Regular' },
  videoEarnings: { alignItems: 'flex-end' },
  videoEarningsAmount: { fontSize: 15, fontFamily: 'Poppins_700Bold' },
  videoEarningsLabel: { fontSize: 10, fontFamily: 'Poppins_400Regular', marginTop: 1 },

  payoutRow: { flexDirection: 'row', alignItems: 'center', gap: 12, paddingVertical: 12 },
  payoutIcon: { width: 38, height: 38, borderRadius: 10, alignItems: 'center', justifyContent: 'center' },
  payoutInfo: { flex: 1 },
  payoutDate: { fontSize: 13, fontFamily: 'Poppins_600SemiBold' },
  payoutMethod: { fontSize: 12, fontFamily: 'Poppins_400Regular', marginTop: 2 },
  payoutRight: { alignItems: 'flex-end', gap: 4 },
  payoutAmount: { fontSize: 14, fontFamily: 'Poppins_700Bold' },
  payoutBadge: { paddingHorizontal: 8, paddingVertical: 2, borderRadius: 6 },
  payoutBadgeText: { fontSize: 11, fontFamily: 'Poppins_600SemiBold' },

  pendingCard: {
    flexDirection: 'row', alignItems: 'center', gap: 12,
    borderRadius: 14, borderWidth: 1, padding: 14,
  },
  pendingTitle: { fontSize: 13, fontFamily: 'Poppins_600SemiBold' },
  pendingSub: { fontSize: 12, fontFamily: 'Poppins_400Regular', marginTop: 2, lineHeight: 16 },
  pendingChange: { fontSize: 13, fontFamily: 'Poppins_700Bold' },
});
