import { View, Text, TouchableOpacity, ScrollView, Alert, ActivityIndicator } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useLocalSearchParams, router } from 'expo-router';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { api } from '../../../services/api';
import { Icon } from '../../../components/Icon';

const STATUS_CONFIG: Record<string, { label: string; color: string; bg: string }> = {
  NEW:        { label: 'New',        color: '#0891B2', bg: '#ECFEFF' },
  CONTACTED:  { label: 'Contacted',  color: '#D97706', bg: '#FEF3C7' },
  INTERESTED: { label: 'Interested', color: '#7C3AED', bg: '#F5F3FF' },
  CONVERTED:  { label: 'Converted',  color: '#166534', bg: '#DCFCE7' },
  LOST:       { label: 'Lost',       color: '#6B7280', bg: '#F1F5F9' },
};

const STATUS_FLOW = ['NEW', 'CONTACTED', 'INTERESTED', 'CONVERTED', 'LOST'];

function InfoRow({ label, value }: { label: string; value?: string | null }) {
  if (!value) return null;
  return (
    <View style={{ paddingVertical: 13, paddingHorizontal: 18, borderBottomWidth: 1, borderBottomColor: '#F1F5F9', flexDirection: 'row', justifyContent: 'space-between' }}>
      <Text style={{ fontSize: 14, color: '#64748B', fontWeight: '500' }}>{label}</Text>
      <Text style={{ fontSize: 14, color: '#1E293B', fontWeight: '600', maxWidth: '60%', textAlign: 'right' }}>{value}</Text>
    </View>
  );
}

export default function LeadDetailScreen() {
  const { id } = useLocalSearchParams<{ id: string }>();
  const qc = useQueryClient();

  const { data: lead, isLoading, refetch } = useQuery({
    queryKey: ['lead', id],
    queryFn: () => api.get(`/api/v1/leads/${id}`).then(r => r.data),
    staleTime: 0,
  });

  const cfg = STATUS_CONFIG[lead?.status ?? 'NEW'] ?? STATUS_CONFIG.NEW;
  const isConverted = lead?.status === 'CONVERTED';

  const updateStatus = async (status: string) => {
    try {
      await api.patch(`/api/v1/leads/${id}`, { status });
      await refetch();
      qc.invalidateQueries({ queryKey: ['leads'] });
    } catch {
      Alert.alert('Error', 'Could not update status.');
    }
  };

  const confirmConvert = () => {
    Alert.alert(
      'Convert to Client?',
      `This will start the onboarding process for ${lead?.firstName} ${lead?.lastName}. They will be added to Clients and an installation ticket will be created.`,
      [
        { text: 'Cancel', style: 'cancel' },
        { text: 'Convert & Onboard', style: 'default', onPress: convertLead },
      ]
    );
  };

  const convertLead = async () => {
    try {
      // Create client from lead
      const clientRes = await api.post('/api/v1/clients', {
        firstName: lead.firstName,
        lastName:  lead.lastName !== '—' ? lead.lastName : '',
        phone:     lead.phone,
        address:   lead.address ?? '—',
        ...(lead.email   ? { email:  lead.email }  : {}),
        ...(lead.areaId  ? { areaId: lead.areaId } : {}),
      });
      const client = clientRes.data;

      // Fetch the auto-created installation ticket (API creates one on client creation)
      let ticket: any = null;
      try {
        const tRes = await api.get(`/api/v1/tickets?clientId=${client.id}&type=INSTALLATION&limit=1`);
        const items = tRes.data?.data ?? tRes.data ?? [];
        ticket = items[0] ?? null;
      } catch {}

      // Mark lead as CONVERTED
      await api.patch(`/api/v1/leads/${id}`, {
        status: 'CONVERTED',
        convertedClientId: client.id,
      });

      qc.invalidateQueries({ queryKey: ['leads'] });
      qc.invalidateQueries({ queryKey: ['clients'] });
      qc.invalidateQueries({ queryKey: ['tasks'] });

      Alert.alert(
        'Lead Converted! 🎉',
        `${lead.firstName} is now a client with an installation ticket created.`,
        [{
          text: 'View Installation Ticket',
          onPress: () => {
            router.replace('/(app)/tasks');
            setTimeout(() => router.push(`/(app)/tasks/${ticket.id}`), 300);
          },
        }, {
          text: 'Done',
          onPress: () => router.back(),
        }]
      );
    } catch (e: any) {
      const msg = e?.response?.data?.message ?? 'Could not convert lead.';
      Alert.alert('Error', Array.isArray(msg) ? msg.join('\n') : msg);
    }
  };

  const confirmDelete = () => {
    Alert.alert(
      'Delete Lead?',
      `Are you sure you want to delete ${lead?.firstName} ${lead?.lastName}? This cannot be undone.`,
      [
        { text: 'Cancel', style: 'cancel' },
        { text: 'Delete', style: 'destructive', onPress: deleteLead },
      ]
    );
  };

  const deleteLead = async () => {
    try {
      await api.delete(`/api/v1/leads/${id}`);
      qc.invalidateQueries({ queryKey: ['leads'] });
      router.back();
    } catch {
      Alert.alert('Error', 'Could not delete lead.');
    }
  };

  if (isLoading) {
    return (
      <SafeAreaView style={{ flex: 1, backgroundColor: '#F8FAFC', alignItems: 'center', justifyContent: 'center' }}>
        <ActivityIndicator color="#0891B2" size="large" />
      </SafeAreaView>
    );
  }

  return (
    <SafeAreaView style={{ flex: 1, backgroundColor: '#F8FAFC' }} edges={['top']}>
      {/* Header */}
      <View style={{ backgroundColor: '#0891B2', paddingHorizontal: 16, paddingVertical: 14, flexDirection: 'row', alignItems: 'center' }}>
        <TouchableOpacity onPress={() => router.back()} hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }} style={{ marginRight: 14 }}>
          <Icon name="arrow-left" size={22} color="#fff" />
        </TouchableOpacity>
        <View style={{ flex: 1 }}>
          <Text style={{ fontSize: 20, fontWeight: '800', color: '#fff' }}>
            {lead?.firstName} {lead?.lastName !== '—' ? lead?.lastName : ''}
          </Text>
          <Text style={{ fontSize: 14, color: '#A5F3FC', marginTop: 1 }}>Lead</Text>
        </View>
        <View style={{ backgroundColor: cfg.bg, borderRadius: 20, paddingHorizontal: 12, paddingVertical: 5 }}>
          <Text style={{ fontSize: 13, fontWeight: '700', color: cfg.color }}>{cfg.label}</Text>
        </View>
      </View>

      <ScrollView contentContainerStyle={{ padding: 16, paddingBottom: 40 }}>
        {/* Info card */}
        <View style={{ backgroundColor: '#fff', borderRadius: 16, marginBottom: 16, borderWidth: 1, borderColor: '#F1F5F9', overflow: 'hidden' }}>
          <InfoRow label="Phone"   value={lead?.phone} />
          <InfoRow label="Email"   value={lead?.email} />
          <InfoRow label="Address" value={lead?.address} />
          <InfoRow label="Area"    value={lead?.area?.name} />
          <InfoRow label="Notes"   value={lead?.notes} />
          <InfoRow label="Added"   value={lead?.createdAt ? new Date(lead.createdAt).toLocaleDateString('en-PH', { dateStyle: 'medium' }) : null} />
        </View>

        {/* Status update */}
        {!isConverted && (
          <View style={{ backgroundColor: '#fff', borderRadius: 16, marginBottom: 16, padding: 16, borderWidth: 1, borderColor: '#F1F5F9' }}>
            <Text style={{ fontSize: 13, fontWeight: '700', color: '#94A3B8', marginBottom: 12, textTransform: 'uppercase', letterSpacing: 0.5 }}>Update Status</Text>
            <View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 8 }}>
              {STATUS_FLOW.filter(s => s !== 'CONVERTED').map(s => {
                const c = STATUS_CONFIG[s];
                const isActive = lead?.status === s;
                return (
                  <TouchableOpacity
                    key={s} onPress={() => !isActive && updateStatus(s)}
                    style={{ paddingHorizontal: 14, paddingVertical: 8, borderRadius: 20, borderWidth: 1.5,
                      borderColor: isActive ? c.color : '#E2E8F0',
                      backgroundColor: isActive ? c.bg : '#F8FAFC' }}
                  >
                    <Text style={{ fontSize: 13, fontWeight: '700', color: isActive ? c.color : '#94A3B8' }}>{c.label}</Text>
                  </TouchableOpacity>
                );
              })}
            </View>
          </View>
        )}

        {/* Action buttons */}
        <View style={{ gap: 12 }}>
          {!isConverted && (
            <TouchableOpacity
              onPress={confirmConvert}
              style={{ backgroundColor: '#059669', borderRadius: 14, paddingVertical: 18, alignItems: 'center', flexDirection: 'row', justifyContent: 'center', gap: 8 }}
            >
              <Text style={{ fontSize: 17, fontWeight: '700', color: '#fff' }}>🚀 Convert to Client & Schedule Install</Text>
            </TouchableOpacity>
          )}

          {isConverted && (
            <View style={{ backgroundColor: '#F0FDF4', borderRadius: 14, paddingVertical: 18, alignItems: 'center', borderWidth: 1.5, borderColor: '#86EFAC' }}>
              <Text style={{ fontSize: 16, fontWeight: '700', color: '#166534' }}>✓ Already Converted to Client</Text>
            </View>
          )}

          <TouchableOpacity
            onPress={confirmDelete}
            style={{ backgroundColor: '#FEF2F2', borderRadius: 14, paddingVertical: 18, alignItems: 'center', borderWidth: 1.5, borderColor: '#FCA5A5' }}
          >
            <Text style={{ fontSize: 16, fontWeight: '700', color: '#DC2626' }}>🗑 Delete Lead</Text>
          </TouchableOpacity>
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}
