import { View, Text, ScrollView, ActivityIndicator, TouchableOpacity, Linking } from 'react-native';
import { useLocalSearchParams, router } from 'expo-router';
import { useQuery } from '@tanstack/react-query';
import { useState } from 'react';
import { api } from '../../../services/api';

export default function ClientDetailScreen() {
  const { id } = useLocalSearchParams<{ id: string }>();
  const [tab, setTab] = useState<'profile' | 'subscription' | 'invoices' | 'payments'>('profile');

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

  const { data: invoices } = useQuery({
    queryKey: ['client-invoices', id],
    queryFn: () => api.get(`/api/v1/invoices?clientId=${id}&limit=20`).then(r => r.data?.data ?? r.data),
    enabled: tab === 'invoices',
  });

  const { data: payments } = useQuery({
    queryKey: ['client-payments', id],
    queryFn: () => api.get(`/api/v1/clients/${id}/payments`).then(r => r.data?.data ?? r.data),
    enabled: tab === 'payments',
  });

  if (isLoading) return <View className="flex-1 items-center justify-center"><ActivityIndicator color="#2563EB" /></View>;

  const TABS = ['profile', 'subscription', 'invoices', 'payments'] as const;

  return (
    <View className="flex-1 bg-gray-50">
      <View className="px-4 pt-14 pb-3 bg-white border-b border-gray-100">
        <TouchableOpacity onPress={() => router.back()} className="mb-2">
          <Text className="text-primary">← Back</Text>
        </TouchableOpacity>
        <Text className="text-xl font-bold text-gray-900">{client?.firstName} {client?.lastName}</Text>
        <Text className="text-gray-500 text-sm">{client?.accountNumber}</Text>
        <View className="flex-row mt-3 gap-2">
          {TABS.map(t => (
            <TouchableOpacity key={t} onPress={() => setTab(t)}
              className={`px-3 py-1.5 rounded-full ${tab === t ? 'bg-primary' : 'bg-gray-100'}`}>
              <Text className={`text-xs font-medium capitalize ${tab === t ? 'text-white' : 'text-gray-600'}`}>{t}</Text>
            </TouchableOpacity>
          ))}
        </View>
      </View>

      <ScrollView className="flex-1 px-4 py-4">
        {tab === 'profile' && (
          <View className="bg-white rounded-2xl border border-gray-100">
            {[
              { label: 'Full Name', value: `${client?.firstName} ${client?.lastName}` },
              { label: 'Phone', value: client?.phone, action: () => Linking.openURL(`tel:${client?.phone}`) },
              { label: 'Email', value: client?.email },
              { label: 'Address', value: client?.address },
              { label: 'Area', value: client?.area?.name },
              { label: 'Status', value: client?.status },
            ].map((row, i) => (
              <TouchableOpacity key={row.label} onPress={row.action}
                className={`px-4 py-3 ${i > 0 ? 'border-t border-gray-100' : ''}`}>
                <Text className="text-gray-500 text-xs mb-0.5">{row.label}</Text>
                <Text className={`text-gray-900 font-medium ${row.action ? 'text-primary' : ''}`}>{row.value ?? '—'}</Text>
              </TouchableOpacity>
            ))}
          </View>
        )}

        {tab === 'subscription' && (
          <View className="bg-white rounded-2xl border border-gray-100 p-4">
            <Text className="font-semibold text-gray-900 mb-3">Current Subscription</Text>
            {client?.subscription ? (
              <>
                <Text className="text-gray-700">Plan: <Text className="font-medium">{client.subscription.plan?.name}</Text></Text>
                <Text className="text-gray-700 mt-1">Status: <Text className="font-medium capitalize">{client.subscription.status}</Text></Text>
                <Text className="text-gray-700 mt-1">Billing Day: <Text className="font-medium">{client.subscription.billingDay}</Text></Text>
                <Text className="text-gray-700 mt-1">Monthly: <Text className="font-medium">₱{client.subscription.plan?.price?.toLocaleString()}</Text></Text>
              </>
            ) : (
              <Text className="text-gray-400">No active subscription</Text>
            )}
          </View>
        )}

        {tab === 'invoices' && (
          <View>
            {(invoices ?? []).map((inv: any) => (
              <View key={inv.id} className="bg-white rounded-xl p-4 mb-2 border border-gray-100">
                <Text className="font-medium text-gray-900">{inv.invoiceNumber}</Text>
                <Text className="text-gray-500 text-sm">₱{inv.totalAmount?.toLocaleString()} · {inv.status}</Text>
              </View>
            ))}
            {!invoices?.length && <Text className="text-gray-400 text-center py-10">No invoices</Text>}
          </View>
        )}

        {tab === 'payments' && (
          <View>
            {(payments ?? []).map((p: any) => (
              <View key={p.id} className="bg-white rounded-xl p-4 mb-2 border border-gray-100">
                <Text className="font-medium text-gray-900">₱{p.amount?.toLocaleString()}</Text>
                <Text className="text-gray-500 text-sm">{p.paymentMethod} · {new Date(p.paymentDate).toLocaleDateString()}</Text>
              </View>
            ))}
            {!payments?.length && <Text className="text-gray-400 text-center py-10">No payments</Text>}
          </View>
        )}
      </ScrollView>
    </View>
  );
}
