import React, { useState } from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  ScrollView,
  ActivityIndicator,
  Alert,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter, useLocalSearchParams } from 'expo-router';
import { useTheme } from '@/constants/ThemeContext';
import { ArrowLeft, Mail, CheckCircle2, RefreshCw } from 'lucide-react-native';
import authService from '@/services/auth';

export default function VerifyAccountScreen() {
  const router = useRouter();
  const { isDark } = useTheme();
  const params = useLocalSearchParams<{ email?: string }>();
  const email = params.email ?? '';

  const [sending, setSending] = useState(false);
  const [checked, setChecked] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleResend = async () => {
    setError(null);
    try {
      setSending(true);
      const res = await authService.resendVerification();
      if (res.status === 'success') {
        Alert.alert(
          'Email Sent',
          'We\'ve resent the verification link to your email. Check your inbox (and spam folder).'
        );
      } else {
        setError(res.message || 'Failed to resend. Please try again.');
      }
    } catch (e: any) {
      console.error('Resend error:', e);
      setError('Something went wrong. Please try again.');
    } finally {
      setSending(false);
    }
  };

  const handleCheckVerification = async () => {
    setError(null);
    try {
      setSending(true);
      const res = await authService.me();

      if (res.user?.email_verified) {
        setChecked(true);
        Alert.alert(
          'Email Verified!',
          'Your email has been verified. You can now log in.',
          [
            {
              text: 'Continue',
              onPress: () => router.replace('/(auth)/login' as any),
            },
          ]
        );
      } else {
        Alert.alert(
          'Not Verified Yet',
          'We don\'t see a verification yet. Please click the link in your email, then try again.'
        );
      }
    } catch (e: any) {
      console.error('Check error:', e);
      setError('Could not verify. Please try again.');
    } finally {
      setSending(false);
    }
  };

  return (
    <SafeAreaView
      style={{
        flex: 1,
        backgroundColor: isDark ? '#050E24' : '#FFFFFF',
      }}
    >
      <ScrollView
        contentContainerStyle={{
          flexGrow: 1,
          paddingHorizontal: 24,
          paddingVertical: 32,
        }}
        showsVerticalScrollIndicator={false}
      >
        {/* Back button */}
        <TouchableOpacity
          onPress={() => router.replace('/(auth)/login' as any)}
          style={{
            flexDirection: 'row',
            alignItems: 'center',
            gap: 6,
            marginBottom: 32,
          }}
          activeOpacity={0.7}
        >
          <ArrowLeft size={20} color={isDark ? '#FFFFFF' : '#0C1C3E'} />
          <Text
            style={{
              color: isDark ? '#FFFFFF' : '#0C1C3E',
              fontWeight: '600',
              fontSize: 15,
            }}
          >
            Back to Login
          </Text>
        </TouchableOpacity>

        {/* Icon */}
        <View
          style={{
            alignSelf: 'center',
            width: 100,
            height: 100,
            borderRadius: 50,
            backgroundColor: isDark ? '#0B1F4D' : '#EFF6FF',
            justifyContent: 'center',
            alignItems: 'center',
            marginBottom: 24,
          }}
        >
          <Mail size={48} color="#38BDF8" />
        </View>

        {/* Title */}
        <Text
          style={{
            fontSize: 26,
            fontWeight: '900',
            color: isDark ? '#FFFFFF' : '#0C1C3E',
            textAlign: 'center',
            marginBottom: 12,
          }}
        >
          Verify your email
        </Text>

        {/* Description */}
        <Text
          style={{
            fontSize: 15,
            color: isDark ? '#94A3B8' : '#64748B',
            textAlign: 'center',
            lineHeight: 22,
            marginBottom: 8,
          }}
        >
          We've sent a verification link to:
        </Text>

        {email ? (
          <Text
            style={{
              fontSize: 16,
              color: '#38BDF8',
              fontWeight: '700',
              textAlign: 'center',
              marginBottom: 28,
            }}
          >
            {email}
          </Text>
        ) : (
          <Text
            style={{
              fontSize: 15,
              color: isDark ? '#94A3B8' : '#64748B',
              textAlign: 'center',
              marginBottom: 28,
            }}
          >
            your registered email address
          </Text>
        )}

        {/* Instructions */}
        <View
          style={{
            backgroundColor: isDark ? '#0B1F4D' : '#F8FAFC',
            borderRadius: 16,
            padding: 20,
            marginBottom: 28,
          }}
        >
          <Text
            style={{
              fontSize: 13,
              fontWeight: '800',
              color: isDark ? '#CBD5E1' : '#475569',
              marginBottom: 12,
              textTransform: 'uppercase',
              letterSpacing: 1,
            }}
          >
            Next steps
          </Text>

          {[
            'Open the email we sent you',
            'Tap the "Verify Email" button',
            'Come back and tap "I\'ve verified"',
          ].map((step, idx) => (
            <View
              key={idx}
              style={{
                flexDirection: 'row',
                alignItems: 'flex-start',
                gap: 10,
                marginBottom: 10,
              }}
            >
              <View
                style={{
                  width: 22,
                  height: 22,
                  borderRadius: 11,
                  backgroundColor: '#38BDF8',
                  justifyContent: 'center',
                  alignItems: 'center',
                  marginTop: 1,
                }}
              >
                <Text
                  style={{
                    color: '#FFFFFF',
                    fontSize: 11,
                    fontWeight: '900',
                  }}
                >
                  {idx + 1}
                </Text>
              </View>
              <Text
                style={{
                  flex: 1,
                  fontSize: 14,
                  color: isDark ? '#CBD5E1' : '#475569',
                  lineHeight: 20,
                }}
              >
                {step}
              </Text>
            </View>
          ))}
        </View>

        {/* Error */}
        {error && (
          <View
            style={{
              backgroundColor: '#FEE2E2',
              padding: 12,
              borderRadius: 8,
              marginBottom: 16,
            }}
          >
            <Text style={{ color: '#991B1B', fontSize: 13 }}>{error}</Text>
          </View>
        )}

        {/* I've verified button */}
        <TouchableOpacity
          onPress={handleCheckVerification}
          disabled={sending}
          activeOpacity={0.88}
          style={{
            backgroundColor: '#0B1F4D',
            height: 52,
            borderRadius: 26,
            justifyContent: 'center',
            alignItems: 'center',
            flexDirection: 'row',
            gap: 8,
            marginBottom: 14,
            opacity: sending ? 0.7 : 1,
          }}
        >
          {sending ? (
            <ActivityIndicator color="#FFFFFF" />
          ) : (
            <>
              <CheckCircle2 size={18} color="#38BDF8" />
              <Text
                style={{ color: '#FFFFFF', fontSize: 15, fontWeight: '800' }}
              >
                I've verified my email
              </Text>
            </>
          )}
        </TouchableOpacity>

        {/* Resend button */}
        <TouchableOpacity
          onPress={handleResend}
          disabled={sending}
          activeOpacity={0.7}
          style={{
            height: 48,
            borderRadius: 24,
            borderWidth: 1.5,
            borderColor: isDark ? '#1E408A' : '#CBD5E1',
            justifyContent: 'center',
            alignItems: 'center',
            flexDirection: 'row',
            gap: 8,
            marginBottom: 24,
            opacity: sending ? 0.7 : 1,
          }}
        >
          <RefreshCw size={16} color={isDark ? '#38BDF8' : '#0B1F4D'} />
          <Text
            style={{
              fontSize: 14,
              fontWeight: '700',
              color: isDark ? '#38BDF8' : '#0B1F4D',
            }}
          >
            Resend verification email
          </Text>
        </TouchableOpacity>

        {/* Hint */}
        <Text
          style={{
            fontSize: 12,
            color: isDark ? '#64748B' : '#94A3B8',
            textAlign: 'center',
            lineHeight: 18,
          }}
        >
          Didn't receive the email? Check your spam folder or try resending.
        </Text>
      </ScrollView>
    </SafeAreaView>
  );
}