import React from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  ScrollView,
} from 'react-native';
import { Stack } from 'expo-router';
import { MaterialIcons, Ionicons } from '@expo/vector-icons';
import { useTheme } from '../hooks/useTheme';
import { useAuth } from '../hooks/useAuth';
import {
  MOCK_MONETIZATION_STATUS,
  MOCK_CREATOR_DASHBOARD,
} from '../constants/mockData';
import { SPACING, TYPOGRAPHY, MONETIZATION } from '../constants/theme';

export default function CreatorDashboardScreen() {
  const { colors } = useTheme();
  const { user } = useAuth();

  if (!user) return null;

  const status = MOCK_MONETIZATION_STATUS;
  const dashboard = MOCK_CREATOR_DASHBOARD;

  const progressPercentage = Math.min(
    (status.yes90d / MONETIZATION.TIER_B_YES_REQUIRED) * 100,
    100
  );

  return (
    <>
      <Stack.Screen
        options={{
          headerShown: true,
          headerTitle: 'Creator Dashboard',
          headerStyle: { backgroundColor: colors.background },
          headerTintColor: colors.text,
          headerShadowVisible: false,
        }}
      />
      <ScrollView style={[styles.container, { backgroundColor: colors.background }]}>
        {/* Earnings Overview */}
        <View style={[styles.card, { backgroundColor: colors.surface }]}>
          <Text style={[styles.cardTitle, { color: colors.text }]}>
            Earnings Overview
          </Text>
          <View style={styles.earningsGrid}>
            <View style={styles.earningItem}>
              <Text style={[styles.earningLabel, { color: colors.textSecondary }]}>
                Total Earnings
              </Text>
              <Text style={[styles.earningAmount, { color: colors.text }]}>
                ${dashboard.totalEarnings.toLocaleString()}
              </Text>
            </View>
            <View style={styles.earningItem}>
              <Text style={[styles.earningLabel, { color: colors.textSecondary }]}>
                This Month
              </Text>
              <Text style={[styles.earningAmount, { color: colors.text }]}>
                ${dashboard.monthlyEarnings.toLocaleString()}
              </Text>
            </View>
          </View>
        </View>

        {/* Next Payout */}
        <View style={[styles.card, { backgroundColor: colors.surface }]}>
          <View style={styles.cardHeader}>
            <Text style={[styles.cardTitle, { color: colors.text }]}>Next Payout</Text>
            <MaterialIcons name="schedule" size={20} color={colors.primary} />
          </View>
          <Text style={[styles.payoutDate, { color: colors.textSecondary }]}>
            {dashboard.nextPayoutDate.toLocaleDateString('en-US', {
              month: 'long',
              day: 'numeric',
              year: 'numeric',
            })}
          </Text>
          <Text style={[styles.payoutAmount, { color: colors.success }]}>
            ${dashboard.nextPayoutAmount.toLocaleString()}
          </Text>
        </View>

        {/* Revenue Breakdown */}
        <View style={[styles.card, { backgroundColor: colors.surface }]}>
          <Text style={[styles.cardTitle, { color: colors.text }]}>
            Revenue Breakdown
          </Text>
          <RevenueItem
            label="Ad Revenue"
            amount={dashboard.adRevenue}
            icon="play-circle"
            colors={colors}
          />
          <RevenueItem
            label="Paid Content"
            amount={dashboard.paidContentRevenue}
            icon="lock"
            colors={colors}
          />
          <RevenueItem
            label="Merchandise"
            amount={dashboard.merchRevenue}
            icon="shopping-bag"
            colors={colors}
          />
          <RevenueItem
            label="Tips & Gifts"
            amount={dashboard.tipsRevenue}
            icon="gift"
            colors={colors}
          />
        </View>

        {/* Monetization Status */}
        <View style={[styles.card, { backgroundColor: colors.surface }]}>
          <View style={styles.cardHeader}>
            <Text style={[styles.cardTitle, { color: colors.text }]}>
              Monetization Status
            </Text>
            <View style={[styles.tierBadge, { backgroundColor: colors.success + '20' }]}>
              <Text style={[styles.tierText, { color: colors.success }]}>
                {status.tier}
              </Text>
            </View>
          </View>

          <View style={styles.statusGrid}>
            <StatusItem
              label="Account Age"
              value={`${status.accountAgeDays} days`}
              isGood={status.requirementsState.accountAge}
              colors={colors}
            />
            <StatusItem
              label="Yes (90d)"
              value={`${status.yes90d} / ${MONETIZATION.TIER_B_YES_REQUIRED}`}
              isGood={status.requirementsState.yesThreshold}
              colors={colors}
            />
            <StatusItem
              label="No (30d)"
              value={`${status.no30d} / ${MONETIZATION.MAX_NO_ALLOWED_30D}`}
              isGood={status.requirementsState.noThreshold}
              colors={colors}
            />
            <StatusItem
              label="KYC"
              value={status.requirementsState.kycCompleted ? 'Completed' : 'Pending'}
              isGood={status.requirementsState.kycCompleted}
              colors={colors}
            />
          </View>

          {/* Progress Bar */}
          <View style={styles.progressContainer}>
            <Text style={[styles.progressLabel, { color: colors.textSecondary }]}>
              Progress to Tier B
            </Text>
            <View style={[styles.progressBar, { backgroundColor: colors.border }]}>
              <View
                style={[
                  styles.progressFill,
                  {
                    backgroundColor: colors.success,
                    width: `${progressPercentage}%`,
                  },
                ]}
              />
            </View>
            <Text style={[styles.progressText, { color: colors.textSecondary }]}>
              {status.yes90d} / {MONETIZATION.TIER_B_YES_REQUIRED} Yes signals
            </Text>
          </View>
        </View>

        {/* Quick Actions */}
        <View style={styles.actionsGrid}>
          <ActionButton
            icon="add-circle"
            label="Create Post"
            colors={colors}
            onPress={() => {}}
          />
          <ActionButton
            icon="bar-chart"
            label="Analytics"
            colors={colors}
            onPress={() => {}}
          />
          <ActionButton
            icon="credit-card"
            label="Debit Card"
            colors={colors}
            onPress={() => {}}
          />
          <ActionButton
            icon="storefront"
            label="Merch"
            colors={colors}
            onPress={() => {}}
          />
        </View>
      </ScrollView>
    </>
  );
}

function RevenueItem({
  label,
  amount,
  icon,
  colors,
}: {
  label: string;
  amount: number;
  icon: string;
  colors: any;
}) {
  return (
    <View style={styles.revenueItem}>
      <View style={styles.revenueLeft}>
        <Ionicons name={icon as any} size={20} color={colors.primary} />
        <Text style={[styles.revenueLabel, { color: colors.text }]}>{label}</Text>
      </View>
      <Text style={[styles.revenueAmount, { color: colors.text }]}>
        ${amount.toLocaleString()}
      </Text>
    </View>
  );
}

function StatusItem({
  label,
  value,
  isGood,
  colors,
}: {
  label: string;
  value: string;
  isGood: boolean;
  colors: any;
}) {
  return (
    <View style={styles.statusItem}>
      <View style={styles.statusHeader}>
        <Text style={[styles.statusLabel, { color: colors.textSecondary }]}>
          {label}
        </Text>
        <MaterialIcons
          name={isGood ? 'check-circle' : 'warning'}
          size={16}
          color={isGood ? colors.success : colors.error}
        />
      </View>
      <Text style={[styles.statusValue, { color: colors.text }]}>{value}</Text>
    </View>
  );
}

function ActionButton({
  icon,
  label,
  colors,
  onPress,
}: {
  icon: string;
  label: string;
  colors: any;
  onPress: () => void;
}) {
  return (
    <TouchableOpacity
      style={[styles.actionButton, { backgroundColor: colors.surface }]}
      onPress={onPress}
    >
      <MaterialIcons name={icon as any} size={28} color={colors.primary} />
      <Text style={[styles.actionLabel, { color: colors.text }]}>{label}</Text>
    </TouchableOpacity>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  card: {
    margin: SPACING.lg,
    padding: SPACING.lg,
    borderRadius: 12,
  },
  cardHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: SPACING.md,
  },
  cardTitle: {
    fontSize: TYPOGRAPHY.sizes.lg,
    fontWeight: TYPOGRAPHY.weights.semibold,
  },
  tierBadge: {
    paddingHorizontal: SPACING.sm,
    paddingVertical: 4,
    borderRadius: 12,
  },
  tierText: {
    fontSize: TYPOGRAPHY.sizes.xs,
    fontWeight: TYPOGRAPHY.weights.semibold,
  },
  earningsGrid: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginTop: SPACING.md,
  },
  earningItem: {
    flex: 1,
  },
  earningLabel: {
    fontSize: TYPOGRAPHY.sizes.sm,
    marginBottom: 4,
  },
  earningAmount: {
    fontSize: TYPOGRAPHY.sizes.xxl,
    fontWeight: TYPOGRAPHY.weights.bold,
  },
  payoutDate: {
    fontSize: TYPOGRAPHY.sizes.sm,
    marginBottom: SPACING.xs,
  },
  payoutAmount: {
    fontSize: TYPOGRAPHY.sizes.xxxl,
    fontWeight: TYPOGRAPHY.weights.bold,
  },
  revenueItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: SPACING.md,
    borderBottomWidth: 1,
    borderBottomColor: 'rgba(0,0,0,0.05)',
  },
  revenueLeft: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: SPACING.sm,
  },
  revenueLabel: {
    fontSize: TYPOGRAPHY.sizes.base,
  },
  revenueAmount: {
    fontSize: TYPOGRAPHY.sizes.base,
    fontWeight: TYPOGRAPHY.weights.semibold,
  },
  statusGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: SPACING.md,
    marginTop: SPACING.md,
  },
  statusItem: {
    flex: 1,
    minWidth: '45%',
  },
  statusHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 4,
  },
  statusLabel: {
    fontSize: TYPOGRAPHY.sizes.xs,
  },
  statusValue: {
    fontSize: TYPOGRAPHY.sizes.base,
    fontWeight: TYPOGRAPHY.weights.semibold,
  },
  progressContainer: {
    marginTop: SPACING.lg,
  },
  progressLabel: {
    fontSize: TYPOGRAPHY.sizes.sm,
    marginBottom: SPACING.xs,
  },
  progressBar: {
    height: 8,
    borderRadius: 4,
    overflow: 'hidden',
  },
  progressFill: {
    height: '100%',
  },
  progressText: {
    fontSize: TYPOGRAPHY.sizes.xs,
    marginTop: SPACING.xs,
  },
  actionsGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    padding: SPACING.lg,
    gap: SPACING.md,
  },
  actionButton: {
    flex: 1,
    minWidth: '45%',
    aspectRatio: 1,
    borderRadius: 12,
    justifyContent: 'center',
    alignItems: 'center',
    gap: SPACING.sm,
  },
  actionLabel: {
    fontSize: TYPOGRAPHY.sizes.sm,
    fontWeight: TYPOGRAPHY.weights.medium,
  },
});