import React, { useEffect, useMemo, useState } from 'react'
import { Check, ChevronLeft, ChevronRight, FileText, Plus, RefreshCw, Trash2, Upload } from 'lucide-react'
import { useTranslation } from 'react-i18next'

import { Modal } from '@/components/ui/modal'
import { api } from '@/lib/api'
import { ENDPOINTS } from '@/constants/endpoints'

export type CustomerKycDocument = {
  id?: string
  file?: File
  file_name: string
  document_type: string
  document_number?: string
  expiry_date?: string
  status?: string
}

type Props = {
  open: boolean
  onClose: () => void
  onSubmit: (data: any) => void
  initialData?: any
  branches: { label: string; value: string }[]
  countries: { label: string; value: string }[]
  isLoading: boolean
  error?: string | null
}

const defaultData = { identity_type: 'national_id', kyc_level: 'basic', kyc_documents: [] }

export function CustomerWizard({ open, onClose, onSubmit, initialData, branches, countries, isLoading, error }: Props) {
  const { t, i18n } = useTranslation()
  const ar = i18n.language?.startsWith('ar')
  const isEdit = Boolean(initialData?.id)
  const [currentStep, setCurrentStep] = useState(1)
  const [formData, setFormData] = useState<any>(defaultData)
  const [documentLoading, setDocumentLoading] = useState(false)

  const labels = useMemo(() => ar ? {
    basic: 'بيانات العميل', identity: 'الهوية', documents: 'المستندات', assignment: 'الفروع', compliance: 'الامتثال', summary: 'الملخص',
  } : {
    basic: 'Customer details', identity: 'Identity', documents: 'Documents', assignment: 'Branches', compliance: 'Compliance', summary: 'Summary',
  }, [ar])
  const steps = Object.values(labels)

  useEffect(() => {
    if (!open) return
    setCurrentStep(1)
    setFormData({
      ...defaultData,
      ...(initialData || {}),
      full_name_ar: initialData?.full_name_ar || initialData?.name || '',
      kyc_documents: [],
    })
    if (!initialData?.id) return
    setDocumentLoading(true)
    api.get(ENDPOINTS.CUSTOMERS.KYC_DOCUMENTS(initialData.id))
      .then((response: any) => {
        const payload = response?.data?.data ?? response?.data ?? response
        const docs = Array.isArray(payload) ? payload.map((doc: any) => ({
          id: doc.id,
          file_name: doc.file_name || doc.document_number || doc.document_type,
          document_type: doc.document_type,
          document_number: doc.document_number || '',
          expiry_date: doc.expiry_date || '',
          status: doc.status,
        })) : []
        setFormData((previous: any) => ({ ...previous, kyc_documents: docs }))
      })
      .catch(() => setFormData((previous: any) => ({ ...previous, kyc_documents: [] })))
      .finally(() => setDocumentLoading(false))
  }, [open, initialData])

  const update = (field: string, value: any) => setFormData((previous: any) => ({ ...previous, [field]: value }))
  const documents: CustomerKycDocument[] = formData.kyc_documents || []
  const addFiles = (files: FileList | null) => {
    if (!files) return
    const additions = Array.from(files).map((file) => ({
      file,
      file_name: file.name,
      document_type: formData.identity_type || 'identity_document',
      document_number: formData.identity_number || '',
      expiry_date: formData.identity_expiry_date || '',
      status: 'new',
    }))
    update('kyc_documents', [...documents, ...additions])
  }
  const updateDocument = (index: number, field: keyof CustomerKycDocument, value: string) => {
    update('kyc_documents', documents.map((document, position) => position === index ? { ...document, [field]: value } : document))
  }
  const removeDocument = (index: number) => update('kyc_documents', documents.filter((_, position) => position !== index))

  const generatePassword = () => {
    const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*'
    update('password', Array.from({ length: 12 }, () => chars[Math.floor(Math.random() * chars.length)]).join(''))
  }

  const fieldClass = 'mt-1.5 h-10 w-full rounded-md border border-border bg-background px-3 text-sm outline-none focus:border-gold-500 disabled:cursor-not-allowed disabled:bg-muted/50 disabled:text-muted-foreground'
  const labelClass = 'block text-xs font-medium'
  const profileComplete = Boolean(formData.full_name_ar && (formData.email || formData.phone) && formData.identity_type && formData.identity_number && formData.identity_country_id)
  const requiredComplete = profileComplete && documents.length > 0

  const content = (() => {
    if (currentStep === 1) return <div className="grid grid-cols-2 gap-4">
      <Field label={ar ? 'الاسم الكامل' : 'Full name'} required><input className={fieldClass} value={formData.full_name_ar || ''} onChange={(e) => update('full_name_ar', e.target.value)} /></Field>
      <Field label={ar ? 'البريد الإلكتروني' : 'Email'}><input type="email" className={fieldClass} value={formData.email || ''} onChange={(e) => update('email', e.target.value)} /></Field>
      <Field label={ar ? 'رقم الهاتف' : 'Phone'}><input className={fieldClass} value={formData.phone || ''} onChange={(e) => update('phone', e.target.value)} /></Field>
      {!isEdit && <Field label={ar ? 'كلمة المرور المؤقتة' : 'Temporary password'} required><div className="relative"><input className={`${fieldClass} pe-10`} value={formData.password || ''} onChange={(e) => update('password', e.target.value)} /><button type="button" onClick={generatePassword} className="absolute end-3 top-1/2 mt-0.5 -translate-y-1/2 text-muted-foreground" title={ar ? 'توليد كلمة مرور' : 'Generate password'}><RefreshCw className="h-4 w-4" /></button></div></Field>}
      <p className="col-span-2 text-xs text-muted-foreground">{ar ? 'يجب إدخال البريد الإلكتروني أو رقم الهاتف على الأقل.' : 'At least an email address or phone number is required.'}</p>
    </div>

    if (currentStep === 2) return <div className="space-y-4">
      {isEdit && <div className="rounded-md border border-blue-200 bg-blue-50 p-3 text-xs text-blue-800">{ar ? 'نوع الهوية ورقمها ودولتها مفاتيح قانونية ثابتة بعد إنشاء العميل. يمكن تعديل تاريخ الانتهاء وإضافة مستند أحدث.' : 'Identity type, number, and country are legal keys and are locked after creation. You can update the expiry date and attach a newer document.'}</div>}
      <div className="grid grid-cols-2 gap-4">
        <Field label={ar ? 'نوع الهوية' : 'Identity type'} required><select disabled={isEdit} className={fieldClass} value={formData.identity_type || ''} onChange={(e) => update('identity_type', e.target.value)}><option value="national_id">{ar ? 'بطاقة شخصية' : 'National ID'}</option><option value="passport">{ar ? 'جواز سفر' : 'Passport'}</option><option value="residence_id">{ar ? 'إقامة' : 'Residence ID'}</option><option value="gcc_id">GCC ID</option><option value="commercial_registration">{ar ? 'سجل تجاري' : 'Commercial registration'}</option><option value="tax_id">{ar ? 'رقم ضريبي' : 'Tax ID'}</option></select></Field>
        <Field label={ar ? 'رقم الهوية' : 'Identity number'} required><input disabled={isEdit} className={fieldClass} value={formData.identity_number || ''} onChange={(e) => update('identity_number', e.target.value)} /></Field>
        <Field label={ar ? 'دولة الهوية' : 'Identity country'} required><select disabled={isEdit} className={fieldClass} value={formData.identity_country_id || ''} onChange={(e) => update('identity_country_id', e.target.value)}><option value="">{ar ? 'اختر الدولة' : 'Select country'}</option>{countries.map((country) => <option key={country.value} value={country.value}>{country.label}</option>)}</select></Field>
        <Field label={ar ? 'تاريخ انتهاء الهوية' : 'Identity expiry'}><input type="date" className={fieldClass} value={formData.identity_expiry_date || ''} onChange={(e) => update('identity_expiry_date', e.target.value)} /></Field>
      </div>
    </div>

    if (currentStep === 3) return <div className="space-y-4">
      <div className="flex items-start justify-between gap-4"><div><h3 className="text-sm font-semibold">{ar ? 'مستندات التحقق' : 'Verification documents'}</h3><p className="mt-1 text-xs text-muted-foreground">{ar ? 'ارفع نسخة واضحة من الهوية أو الجواز. الصيغ المدعومة PDF وJPG وPNG وWebP بحد أقصى 10 ميجابايت.' : 'Upload clear identity evidence. PDF, JPG, PNG, and WebP are supported up to 10 MB.'}</p></div><label className="inline-flex h-9 cursor-pointer items-center gap-2 rounded-md bg-gold-500 px-3 text-xs font-semibold text-ink-900 hover:bg-gold-600"><Upload className="h-4 w-4" />{ar ? 'إضافة مستند' : 'Add document'}<input type="file" multiple accept="application/pdf,image/jpeg,image/png,image/webp" className="hidden" onChange={(e) => addFiles(e.target.files)} /></label></div>
      {documentLoading ? <p className="py-8 text-center text-xs text-muted-foreground">{ar ? 'جارٍ تحميل المستندات...' : 'Loading documents...'}</p> : !documents.length ? <div className="border border-dashed border-amber-300 bg-amber-50 p-6 text-center text-xs text-amber-800">{ar ? 'لم تتم إضافة مستندات. سيظهر الطلب في KYC كملف غير مكتمل.' : 'No documents added. The KYC application will be marked incomplete for review.'}</div> : <div className="space-y-3">{documents.map((document, index) => <div key={document.id || `${document.file_name}-${index}`} className="border-b border-border pb-3"><div className="mb-3 flex items-center gap-2"><FileText className="h-4 w-4 text-gold-600" /><span className="min-w-0 flex-1 truncate text-xs font-semibold">{document.file_name}</span>{document.status && <span className="text-[11px] text-muted-foreground">{document.status}</span>}{!document.id && <button type="button" onClick={() => removeDocument(index)} title={ar ? 'إزالة' : 'Remove'}><Trash2 className="h-4 w-4 text-red-600" /></button>}</div><div className="grid grid-cols-3 gap-3"><Field label={ar ? 'نوع المستند' : 'Document type'}><select disabled={Boolean(document.id)} className={fieldClass} value={document.document_type} onChange={(e) => updateDocument(index, 'document_type', e.target.value)}><option value="national_id">{ar ? 'بطاقة شخصية' : 'National ID'}</option><option value="passport">{ar ? 'جواز سفر' : 'Passport'}</option><option value="residence_id">{ar ? 'إقامة' : 'Residence ID'}</option><option value="commercial_registration">{ar ? 'سجل تجاري' : 'Commercial registration'}</option><option value="other">{ar ? 'أخرى' : 'Other'}</option></select></Field><Field label={ar ? 'رقم المستند' : 'Document number'}><input disabled={Boolean(document.id)} className={fieldClass} value={document.document_number || ''} onChange={(e) => updateDocument(index, 'document_number', e.target.value)} /></Field><Field label={ar ? 'تاريخ الانتهاء' : 'Expiry date'}><input disabled={Boolean(document.id)} type="date" className={fieldClass} value={document.expiry_date || ''} onChange={(e) => updateDocument(index, 'expiry_date', e.target.value)} /></Field></div></div>)}</div>}
    </div>

    if (currentStep === 4) return <div className="grid grid-cols-2 gap-4">
      <Field label={ar ? 'فرع التسجيل' : 'Registration branch'}><select disabled={isEdit} className={fieldClass} value={formData.registered_at_branch_id || ''} onChange={(e) => update('registered_at_branch_id', e.target.value)}><option value="">{ar ? 'اختر الفرع' : 'Select branch'}</option>{branches.map((branch) => <option key={branch.value} value={branch.value}>{branch.label}</option>)}</select></Field>
      <Field label={ar ? 'الفرع الرئيسي' : 'Primary branch'}><select className={fieldClass} value={formData.primary_branch_id || ''} onChange={(e) => update('primary_branch_id', e.target.value)}><option value="">{ar ? 'اختر الفرع' : 'Select branch'}</option>{branches.map((branch) => <option key={branch.value} value={branch.value}>{branch.label}</option>)}</select></Field>
      {isEdit && <p className="col-span-2 text-xs text-muted-foreground">{ar ? 'فرع التسجيل ثابت لأغراض التدقيق، بينما يمكن تغيير الفرع الرئيسي.' : 'The registration branch is audit-locked; the primary branch remains editable.'}</p>}
    </div>

    if (currentStep === 5) return <div className="space-y-4"><Field label={ar ? 'مستوى KYC' : 'KYC level'} required><select className={fieldClass} value={formData.kyc_level || 'basic'} onChange={(e) => update('kyc_level', e.target.value)}><option value="basic">{ar ? 'أساسي' : 'Basic'}</option><option value="intermediate">{ar ? 'متوسط' : 'Intermediate'}</option><option value="premium">{ar ? 'متقدم' : 'Premium'}</option></select></Field><div className="rounded-md border border-border bg-muted/30 p-3 text-xs text-muted-foreground">{ar ? 'نتائج مكافحة غسل الأموال ودرجة المخاطر تُدار من شاشة KYC بعد إنشاء العميل، ولا يتم إدخالها يدوياً هنا.' : 'AML screening and risk scoring are managed from the KYC review after customer creation; they are not entered manually here.'}</div></div>

    return <div className="space-y-3 text-sm"><Summary label={ar ? 'الاسم' : 'Name'} value={formData.full_name_ar} /><Summary label={ar ? 'التواصل' : 'Contact'} value={formData.email || formData.phone} /><Summary label={ar ? 'الهوية' : 'Identity'} value={`${formData.identity_type || '-'} · ${formData.identity_number || '-'}`} /><Summary label={ar ? 'مستوى KYC' : 'KYC level'} value={formData.kyc_level} /><Summary label={ar ? 'المستندات' : 'Documents'} value={String(documents.length)} />{!profileComplete && <div className="rounded-md border border-red-200 bg-red-50 p-3 text-xs text-red-700">{ar ? 'أكمل الاسم ووسيلة التواصل وبيانات الهوية قبل الحفظ.' : 'Complete the name, contact method, and identity fields before saving.'}</div>}{documents.length === 0 && <div className="rounded-md border border-amber-200 bg-amber-50 p-3 text-xs text-amber-800">{ar ? 'أضف مستند تحقق واحداً على الأقل قبل الحفظ.' : 'Add at least one verification document before saving.'}</div>}{error && <div className="rounded-md border border-red-200 bg-red-50 p-3 text-xs text-red-700">{error}</div>}</div>
  })()

  return <Modal open={open} onClose={onClose} title={isEdit ? (ar ? 'تعديل ملف العميل' : 'Edit customer') : (ar ? 'إنشاء عميل جديد' : 'Create customer')} description={ar ? 'أكمل ملف العميل ومستندات التحقق في مسار واحد.' : 'Complete the customer profile and verification documents in one flow.'} size="lg">
    <div className="mt-4 flex min-h-[430px] gap-6"><div className="w-44 shrink-0 space-y-1">{steps.map((step, index) => { const number = index + 1; const active = number === currentStep; const past = number < currentStep; return <button type="button" key={step} onClick={() => setCurrentStep(number)} className={`flex w-full items-center gap-3 rounded-md px-3 py-2 text-start text-xs ${active ? 'bg-gold-500/10 font-semibold text-gold-700' : 'text-muted-foreground hover:bg-muted'}`}><span className={`flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-[10px] ${active ? 'bg-gold-500 text-ink-900' : past ? 'bg-emerald-100 text-emerald-700' : 'bg-muted'}`}>{past ? <Check className="h-3 w-3" /> : number}</span>{step}</button> })}</div><div className="flex min-w-0 flex-1 flex-col"><div className="flex-1 overflow-y-auto px-1">{content}</div><div className="mt-6 flex items-center justify-between border-t border-border pt-4"><button type="button" disabled={currentStep === 1 || isLoading} onClick={() => setCurrentStep((step) => step - 1)} className="inline-flex h-9 items-center gap-1 rounded-md border border-border px-3 text-xs font-medium disabled:opacity-50"><ChevronLeft className="h-4 w-4" />{ar ? 'السابق' : 'Back'}</button>{currentStep < steps.length ? <button type="button" onClick={() => setCurrentStep((step) => step + 1)} className="inline-flex h-9 items-center gap-1 rounded-md bg-gold-500 px-4 text-xs font-semibold text-ink-900"><span>{ar ? 'التالي' : 'Next'}</span><ChevronRight className="h-4 w-4" /></button> : <button type="button" disabled={isLoading || !requiredComplete} onClick={() => onSubmit(formData)} className="inline-flex h-9 items-center gap-2 rounded-md bg-gold-500 px-4 text-xs font-semibold text-ink-900 disabled:opacity-50"><Check className="h-4 w-4" />{isLoading ? (ar ? 'جارٍ الحفظ...' : 'Saving...') : (ar ? 'حفظ الملف' : 'Save profile')}</button>}</div></div></div>
  </Modal>
}

function Field({ label, required, children }: { label: string; required?: boolean; children: React.ReactNode }) {
  return <label className="block text-xs font-medium"><span>{label}{required ? ' *' : ''}</span>{children}</label>
}

function Summary({ label, value }: { label: string; value: string | undefined }) {
  return <div className="flex items-center justify-between gap-4 border-b border-border pb-2"><span className="text-muted-foreground">{label}</span><span className="font-medium">{value || '-'}</span></div>
}
