'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import { PageHeader } from '@/components/ui/page-header';
import { KpiCard } from '@/components/ui/kpi-card';
import { SectionCard } from '@/components/ui/section-card';
import { FilterToolbar } from '@/components/ui/filter-toolbar';
import { StatusBadge } from '@/components/ui/status-badge';
import { AvatarBadge } from '@/components/ui/avatar-badge';
import { Users, UserCheck, UserX, Clock, Plus, Download, ChevronLeft, ChevronDown, ChevronUp, IdCard, UserRound, RefreshCw, Info } from 'lucide-react';
import { useCustomers, CustomerCreateDTO, CustomerUpdateDTO } from '@/hooks';
import { useBranches } from '@/hooks/useBranches';
import { ErrorMessage } from '@/components/ErrorMessage';
import { formatMoney, formatNumber, timeAgo } from '@/lib/format';
import { CustomerWizard } from '@/components/customer/customer-wizard';
import { api } from '@/lib/api';
import { ENDPOINTS } from '@/constants/endpoints';
import type { FormField } from '@/types/base';
import i18n from "@/lib/i18n";
import { LOCAL_COUNTRIES } from '@/lib/countries';
import { uploadCustomerKycDocuments } from '@/lib/kyc-documents';

function generateTemporaryPassword() {
  const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*';
  let password = '';
  for (let i = 0; i < 12; i++) {
    password += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return password;
}

const KYC_LEVEL_LABEL: Record<string, { label: string; tone: 'success' | 'pending' | 'danger' | 'warning' | 'info' | 'neutral' }> = {
  basic: { label: i18n.t('app.admin.customers.page.text_58'), tone: 'info' },
  intermediate: { label: i18n.t('app.admin.customers.page.text_59'), tone: 'warning' },
  premium: { label: i18n.t('app.admin.customers.page.text_60'), tone: 'success' },
};

const STATUS_LABEL: Record<string, { label: string; tone: 'success' | 'warning' | 'danger' | 'neutral' }> = {
  draft: { label: 'Draft', tone: 'neutral' },
  pending_kyc: { label: i18n.t('app.admin.customers.page.text_10'), tone: 'warning' },
  active: { label: i18n.t('app.admin.customers.page.text_7'), tone: 'success' },
  suspended: { label: i18n.t('app.admin.customers.page.text_8'), tone: 'danger' },
  rejected: { label: 'Rejected', tone: 'danger' },
  closed: { label: i18n.t('app.admin.customers.page.text_62'), tone: 'neutral' },
  blocked: { label: i18n.t('app.admin.customers.page.text_61'), tone: 'danger' },
  archived: { label: i18n.t('app.admin.customers.page.text_62'), tone: 'neutral' },
  pending: { label: i18n.t('app.admin.customers.page.text_10'), tone: 'warning' },
};

const TIER_LABEL: Record<string, string> = {
  retail: i18n.t('app.admin.customers.page.text_11'),
  premium: i18n.t('app.admin.customers.page.text_12'),
  institutional: i18n.t('app.admin.customers.page.text_13'),
};

const KYC_LEVEL_OPTIONS = [
  { label: i18n.t('app.admin.customers.page.text_58'), value: 'basic' },
  { label: i18n.t('app.admin.customers.page.text_59'), value: 'intermediate' },
  { label: i18n.t('app.admin.customers.page.text_60'), value: 'premium' },
]

const IDENTITY_TYPE_OPTIONS = [
  { label: i18n.t('app.admin.customers.page.text_67'), value: 'national_id' },
  { label: i18n.t('app.admin.customers.page.text_68'), value: 'passport' },
  { label: i18n.t('app.admin.customers.page.text_69'), value: 'residence_id' },
  { label: i18n.t('app.admin.customers.page.text_70'), value: 'gcc_id' },
  { label: i18n.t('app.admin.customers.page.text_71'), value: 'commercial_registration' },
  { label: i18n.t('app.admin.customers.page.text_72'), value: 'tax_id' },
]

const CUSTOMER_UPDATE_FIELDS: FormField[] = [
  { name: 'kyc_level', label: i18n.t('app.admin.customers.page.text_51'), type: 'select', required: true, options: KYC_LEVEL_OPTIONS },
  { name: 'identity_expiry_date', label: i18n.t('app.admin.customers.page.text_64'), type: 'date' },
  { name: 'primary_branch_id', label: i18n.t('app.admin.customers.page.text_66'), type: 'text' },
];

export default function CustomersPage() {
  const {
    items,
    isLoading,
    error,
    totalCount,
    fetchItems,
    updateItem,
    setIsLoading,
    setError,
  } = useCustomers();

  const { items: branches, fetchItems: fetchBranches } = useBranches();
  const [countries, setCountries] = useState<{label: string, value: string}[]>([]);
  const [countriesLoaded, setCountriesLoaded] = useState(false);

  useEffect(() => {
    fetchBranches(1, 100);
    
    api.get(ENDPOINTS.COUNTRIES.LIST, { params: { limit: 300 } }).then(res => {
      const raw = res.data ?? res.items ?? res;
      const list = Array.isArray(raw) ? raw : [];
      if (list.length > 0) {
        setCountries(list.map((c: any) => ({
          label: c.name_ar || c.name || c.label,
          value: c.id || c.value
        })));
      } else {
        setCountries(LOCAL_COUNTRIES);
      }
      setCountriesLoaded(true);
    }).catch(() => {
      setCountries(LOCAL_COUNTRIES);
      setCountriesLoaded(true);
    });
  }, [fetchBranches]);

  const branchOptions = branches.map((branch) => {
    const b = branch as any
    return {
      label: `${i18n.language?.startsWith('ar') ? (b.name_ar || b.name_en || b.name) : (b.name_en || b.name || b.name_ar)} (${b.code})`,
      value: b.id
    }
  });

  const countriesUseUuid = countries.length > 0 && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(countries[0].value);

  const [searchValue, setSearchValue] = useState('');
  const [statusFilter, setStatusFilter] = useState('');
  const [kycLevelFilter, setKycLevelFilter] = useState('');
  const [activeCount, setActiveCount] = useState(0);
  const [pendingCount, setPendingCount] = useState(0);
  const [suspendedCount, setSuspendedCount] = useState(0);

  // Modal State
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingCustomer, setEditingCustomer] = useState<any | null>(null);
  const [formErrors, setFormErrors] = useState<Record<string, string>>({});

  useEffect(() => {
    const timer = window.setTimeout(() => {
      fetchItems(1, 50, searchValue, {
        status: statusFilter,
        kyc_level: kycLevelFilter,
      });
    }, 250);

    return () => window.clearTimeout(timer);
  }, [fetchItems, searchValue, statusFilter, kycLevelFilter]);

  useEffect(() => {
    setActiveCount(items.filter((c: any) => c.status === 'active').length);
    setPendingCount(items.filter((c: any) => c.status === 'pending_kyc' || c.status === 'pending' || c.status === 'draft').length);
    setSuspendedCount(items.filter((c: any) => c.status === 'suspended').length);
  }, [items]);

  const handleOpenModal = (customer?: any) => {
    setEditingCustomer(customer || null);
    setFormErrors({});
    setIsModalOpen(true);
  };

  const handleCloseModal = () => {
    setIsModalOpen(false);
    setEditingCustomer(null);
    setFormErrors({});
  };

  const handleSubmitWizard = async (data: any) => {
    // Validate UUID fields before submitting
    const countryVal = String(data.identity_country_id || '');
    if (countryVal && !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(countryVal)) {
      setFormErrors({ _global: i18n.t('app.admin.customers.page.text_80') || 'Invalid country selected. Please select a country from the dropdown list.' });
      return;
    }

    try {
      if (editingCustomer) {
        const payload: CustomerUpdateDTO = {
          full_name_ar: data.full_name_ar || null,
          email: data.email || null,
          phone: data.phone || null,
          kyc_level: data.kyc_level || undefined,
          identity_expiry_date: data.identity_expiry_date || null,
          primary_branch_id: data.primary_branch_id || null,
        };
        const ok = await updateItem(editingCustomer.id, payload);
        if (!ok) return;
        await uploadCustomerKycDocuments(editingCustomer.id, data.kyc_documents);
      } else {
        const payload: CustomerCreateDTO = {
          email: data.email ? String(data.email) : null,
          phone: data.phone ? String(data.phone) : null,
          password: data.password ? String(data.password) : null,
          full_name_ar: data.full_name_ar ? String(data.full_name_ar) : null,
          identity_type: (data.identity_type || 'national_id') as CustomerCreateDTO['identity_type'],
          identity_number: String(data.identity_number || ''),
          identity_country_id: String(data.identity_country_id || ''),
          identity_expiry_date: data.identity_expiry_date ? String(data.identity_expiry_date) : null,
          kyc_level: (data.kyc_level || 'basic') as CustomerCreateDTO['kyc_level'],
          registered_at_branch_id: data.registered_at_branch_id ? String(data.registered_at_branch_id) : null,
          primary_branch_id: data.primary_branch_id ? String(data.primary_branch_id) : null,
        };
        setIsLoading(true);
        setError(null);
        const response: any = await api.post(ENDPOINTS.CUSTOMERS.CREATE, payload);
        const created = response?.data?.data ?? response?.data ?? response;
        if (!created?.id) throw new Error('Customer was created but its identifier was not returned.');
        await uploadCustomerKycDocuments(created.id, data.kyc_documents);
        window.dispatchEvent(new Event('kyc-applications-updated'));
      }
      handleCloseModal();
      fetchItems(1, 50, searchValue, { status: statusFilter, kyc_level: kycLevelFilter });
    } catch (err: any) {
      let errorMessage = err.message || i18n.t('app.admin.customers.page.text_23');
      
      if (err.response?.data) {
        const data = err.response.data;
        if (data.message) {
          try {
            const parsed = typeof data.message === 'string' && (data.message.startsWith('[') || data.message.startsWith('{')) 
              ? JSON.parse(data.message.replace(/'/g, '"')) 
              : data.message;
            
            if (Array.isArray(parsed)) {
              errorMessage = parsed.map((e: any) => `${e.loc?.join('.')}: ${e.msg}`).join('\n');
            } else if (typeof parsed === 'object') {
              errorMessage = Object.entries(parsed).map(([k, v]) => `${k}: ${v}`).join('\n');
            } else {
              errorMessage = String(parsed);
            }
          } catch {
            errorMessage = data.message;
          }
        } else if (data.detail) {
          errorMessage = typeof data.detail === 'string' ? data.detail : JSON.stringify(data.detail);
        }
      }
      
      setFormErrors({ _global: errorMessage });
    } finally {
      setIsLoading(false);
    }
  };



  if (error && !isModalOpen) return <ErrorMessage message={error} />;

  return (
    <>
      <PageHeader
        breadcrumbs={[{ label: i18n.t('app.admin.customers.page.text_24'), href: '/' }, { label: i18n.t('app.admin.customers.page.text_25') }]}
        title={i18n.t('app.admin.customers.page.text_26')}
        description={i18n.t('app.admin.customers.page.text_27')}
        actions={
          <>
            <button className='h-9 px-3 rounded-lg border border-border bg-card text-[12.5px] font-medium hover:bg-muted transition inline-flex items-center gap-1.5'>
              <Download className='h-4 w-4' />
              {i18n.t('app.admin.customers.page.text_46')}</button>
            <button 
              onClick={() => handleOpenModal()}
              className='h-9 px-4 rounded-lg bg-gold-500 hover:bg-gold-600 text-white text-[12.5px] font-semibold shadow-sm inline-flex items-center gap-1.5 transition'
            >
              <Plus className='h-4 w-4' />
              {i18n.t('app.admin.customers.page.text_47')}</button>
          </>
        }
      />

      <div className='grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 mb-4'>
        <KpiCard label={i18n.t('app.admin.customers.page.text_28')} value={formatNumber(totalCount, 0)} icon={Users} tone='gold' accent />
        <KpiCard label={i18n.t('app.admin.customers.page.text_29')} value={formatNumber(activeCount, 0)} icon={UserCheck} tone='success' />
        <KpiCard label={i18n.t('app.admin.customers.page.text_30')} value={formatNumber(pendingCount, 0)} icon={Clock} tone='warning' />
        <KpiCard label={i18n.t('app.admin.customers.page.text_31')} value={formatNumber(suspendedCount, 0)} icon={UserX} tone='danger' />
      </div>

      <FilterToolbar
        searchPlaceholder={i18n.t('app.admin.customers.page.text_32')}
        searchValue={searchValue}
        onSearchChange={setSearchValue}
        showDate={false}
        showFilterIcon={false}
        showExport={false}
        customFilters={
          <>
            <select
              value={kycLevelFilter}
              onChange={(event) => setKycLevelFilter(event.target.value)}
              className="h-9 rounded-md border border-border bg-card px-3 text-[12.5px] font-medium text-foreground"
            >
              <option value="">{i18n.t('app.admin.customers.page.text_35')}: {i18n.t('app.admin.customers.page.text_36')}</option>
              {KYC_LEVEL_OPTIONS.map((option) => (
                <option key={option.value} value={option.value}>{option.label}</option>
              ))}
            </select>
            <select
              value={statusFilter}
              onChange={(event) => setStatusFilter(event.target.value)}
              className="h-9 rounded-md border border-border bg-card px-3 text-[12.5px] font-medium text-foreground"
            >
              <option value="">{i18n.t('app.admin.customers.page.text_37')}: {i18n.t('app.admin.customers.page.text_38')}</option>
              {Object.entries(STATUS_LABEL).map(([value, status]) => (
                <option key={value} value={value}>{status.label}</option>
              ))}
            </select>
          </>
        }
      />

      <SectionCard padded={false} title={i18n.t('app.admin.customers.page.text_39')} description={i18n.t('app.admin.customers.page.text_count', { count: items.length })}>
        <div className='overflow-x-auto'>
          <table className='w-full text-right border-collapse'>
            <thead>
              <tr className='bg-muted/40 border-b border-border'>
                <th className='px-4 py-3 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground'>{i18n.t('app.admin.customers.page.text_48')}</th>
                <th className='px-4 py-3 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground'>{i18n.t('app.admin.customers.page.text_49')}</th>
                <th className='px-4 py-3 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground'>{i18n.t('app.admin.customers.page.text_50')}</th>
                <th className='px-4 py-3 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground'>{i18n.t('app.admin.customers.page.text_51')}</th>
                <th className='px-4 py-3 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground'>{i18n.t('app.admin.customers.page.text_52')}</th>
                <th className='px-4 py-3 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground'>{i18n.t('app.admin.customers.page.text_53')}</th>
                <th className='px-4 py-3 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground'>{i18n.t('app.admin.customers.page.text_54')}</th>
                <th className='px-4 py-3 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground'>{i18n.t('app.admin.customers.page.text_55')}</th>
                <th className='px-4 py-3' />
              </tr>
            </thead>
            <tbody>
              {isLoading ? (
                <tr>
                  <td colSpan={9} className='px-4 py-8 text-center'>
                    <div className='flex justify-center'>
                      <div className='animate-spin rounded-full h-8 w-8 border-b-2 border-primary'></div>
                    </div>
                  </td>
                </tr>
              ) : items.length === 0 ? (
                <tr>
                  <td colSpan={9} className='px-5 py-8 text-center text-[12.5px] text-muted-foreground'>
                    {i18n.t('app.admin.customers.page.text_56')}</td>
                </tr>
              ) : (
                items.map((c: any) => {
                  const kyc = KYC_LEVEL_LABEL[c.kyc_level] ?? { label: c.kyc_level || '—', tone: 'neutral' as const };
                  const status = STATUS_LABEL[c.status] ?? { label: c.status, tone: 'neutral' as const };
                  const cash = (c as any).cash_wallets?.[0]?.available_balance ?? (c as any).available_balance ?? 0;
                  const gold = (c as any).gold_wallets?.[0]?.available_grams ?? (c as any).available_grams ?? 0;
                  const displayName = c.name || c.email || c.phone || c.user_id?.slice(0, 8) || '—';
                  return (
                    <tr key={c.id} className='border-b border-border/70 hover:bg-muted/30 transition'>
                      <td className='px-4 py-3 text-[12.5px] font-semibold text-gold-700 tabular-nums'>{c.customer_code || c.id.slice(0, 8)}</td>
                      <td className='px-4 py-3'>
                        <div className='flex items-center gap-2.5'>
                          <AvatarBadge name={displayName} size='sm' />
                          <div>
                            <div className='text-[12.5px] font-semibold text-foreground hover:text-gold-600 cursor-pointer' onClick={() => handleOpenModal(c)}>{displayName}</div>
                            <div className='text-[11px] text-muted-foreground'>{c.email || c.phone || c.user_id}</div>
                          </div>
                        </div>
                      </td>
                      <td className='px-4 py-3 text-[12px] text-muted-foreground'>{TIER_LABEL[c.tier] ?? c.tier ?? c.identity_type}</td>
                      <td className='px-4 py-3'><StatusBadge tone={kyc.tone} size='sm'>{kyc.label}</StatusBadge></td>
                      <td className='px-4 py-3'><StatusBadge tone={status.tone} size='sm'>{status.label}</StatusBadge></td>
                      <td className='px-4 py-3 text-[12.5px] tabular-nums font-medium'>{formatMoney(Number(cash))}</td>
                      <td className='px-4 py-3 text-[12.5px] tabular-nums font-medium'>{formatNumber(Number(gold), 2)}</td>
                      <td className='px-4 py-3 text-[11.5px] text-muted-foreground'>{timeAgo(c.last_login_at)}</td>
                      <td className='px-4 py-3'>
                        <Link href={`/customers/${c.id}`} className='text-[11.5px] font-semibold text-gold-600 hover:text-gold-700 inline-flex items-center gap-0.5'>
                          {i18n.t('app.admin.customers.page.text_57')}<ChevronLeft className='h-3.5 w-3.5' />
                        </Link>
                      </td>
                    </tr>
                  );
                })
              )}
            </tbody>
          </table>
        </div>
      </SectionCard>

      <CustomerWizard
        open={isModalOpen}
        onClose={handleCloseModal}
        onSubmit={handleSubmitWizard}
        initialData={editingCustomer}
        branches={branchOptions}
        countries={countries}
        isLoading={isLoading}
        error={formErrors._global || error}
      />
    </>
  );
}
