'use client';

import { useState } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { useToast } from '@/hooks/use-toast';
import { useDocumentLock } from '@/hooks/use-document-lock';
import { DocumentLockBanner } from '@/components/admin/document-lock-banner';
import { Customer, Supplier } from '@/lib/types';
import Link from 'next/link';

interface EndorseCheckDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  checkId: string;
  checkNumber: string;
  amount: number;
  customers: Customer[];
  suppliers: Supplier[];
  collectionAccountsReady?: boolean;
  t: any;
}

export function EndorseCheckDialog({
  open,
  onOpenChange,
  checkId,
  checkNumber,
  amount,
  customers,
  suppliers,
  collectionAccountsReady = true,
  t,
}: EndorseCheckDialogProps) {
  const [activeTab, setActiveTab] = useState<'party' | 'collection'>('party');
  const [selectedPartyId, setSelectedPartyId] = useState<string>('');
  const [selectedPartyType, setSelectedPartyType] = useState<'customer' | 'supplier'>('customer');
  const [notes, setNotes] = useState('');
  const [endorsementReference, setEndorsementReference] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);

  const { toast } = useToast();
  const { lockStatus } = useDocumentLock('check', checkId, { enabled: open });
  const isEditLocked = lockStatus.isLocked;

  const parties = [
    ...customers.map(c => ({
      id: c.id,
      name: c.name,
      type: 'customer' as const,
      balance: c.balance
    })),
    ...suppliers.map(s => ({
      id: s.id,
      name: s.name,
      type: 'supplier' as const,
      balance: s.balance
    }))
  ];

  const selectedParty = parties.find(
    p => p.id === selectedPartyId && p.type === selectedPartyType
  );

  const handleEndorseToParty = async () => {
    if (isEditLocked) { return; }
    if (!selectedParty) {
      toast({
        title: t?.error ?? 'خطأ',
        description: t?.selectParty ?? 'يرجى اختيار جهة',
        variant: 'destructive'
      });
      return;
    }

    setIsSubmitting(true);
    try {
      const response = await fetch('/api/admin/checks/endorse', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          checkId,
          endorsementType: 'endorsed-to-party',
          endorsedToId: selectedParty.id,
          endorsedToName: selectedParty.name,
          endorsedToType: selectedParty.type,
          endorsementReference: endorsementReference.trim() || undefined,
          notes
        })
      });

      if (!response.ok) throw new Error('فشل تجيير الشيك');

      toast({
        title: t?.success ?? 'تم بنجاح',
        description: `${t?.checkEndorsedTo ?? 'تم تجيير الشيك إلى'} ${selectedParty.name}`,
      });

      onOpenChange(false);
      window.location.reload();
    } catch (error) {
      toast({
        title: t?.error ?? 'خطأ',
        description: error instanceof Error ? error.message : 'فشل تجيير الشيك',
        variant: 'destructive'
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleTransferToCollection = async () => {
    if (isEditLocked) { return; }
    if (!collectionAccountsReady) {
      toast({
        title: t?.error ?? 'خطأ',
        description: t?.collectionAccountsMissing ?? 'لا يمكن التحويل قبل إنشاء حسابات التحصيل المطلوبة.',
        variant: 'destructive'
      });
      return;
    }
    setIsSubmitting(true);
    try {
      const response = await fetch('/api/admin/checks/endorse', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          checkId,
          endorsementType: 'transferred-to-collection',
          notes
        })
      });

      const payload = await response.json().catch(() => ({}));
      if (!response.ok) {
        if (payload?.error === 'COLLECTION_ACCOUNTS_MISSING') {
          throw new Error('حسابات التحصيل غير مكتملة. أنشئ حساب 1015 (شيكات واردة) وحساب 1020 (شيكات برسم التحصيل).');
        }
        throw new Error(payload?.error || 'فشل تحويل الشيك');
      }

      toast({
        title: t?.success ?? 'تم بنجاح',
        description: t?.checkTransferredToCollection ?? 'تم تحويل الشيك إلى التحصيل',
      });

      onOpenChange(false);
      window.location.reload();
    } catch (error) {
      toast({
        title: t?.error ?? 'خطأ',
        description: error instanceof Error ? error.message : 'فشل تحويل الشيك',
        variant: 'destructive'
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle>{t?.endorseCheck ?? 'تجيير الشيك'}</DialogTitle>
          <DialogDescription>
            {t?.checkNumber ?? 'رقم الشيك'}: {checkNumber} - {t?.amount ?? 'المبلغ'}: {amount}
          </DialogDescription>
        </DialogHeader>
        <DocumentLockBanner lockStatus={lockStatus} />

        <Tabs dir="rtl" value={activeTab} onValueChange={(v) => setActiveTab(v as 'party' | 'collection')} className="w-full text-right">
          <TabsList className="grid w-full grid-cols-2">
            <TabsTrigger value="party">{t?.endorseToParty ?? 'تجيير إلى جهة'}</TabsTrigger>
            <TabsTrigger value="collection">{t?.transferToCollection ?? 'تحويل للتحصيل'}</TabsTrigger>
          </TabsList>

          <TabsContent value="party" className="space-y-4">
            <div className="space-y-2">
              <Label>{t?.selectParty ?? 'اختيار الجهة'}</Label>
              <div className="flex gap-2">
                <select
                  value={selectedPartyType}
                  onChange={(e) => {
                    setSelectedPartyType(e.target.value as 'customer' | 'supplier');
                    setSelectedPartyId('');
                  }}
                  className="w-1/4 px-3 py-2 border rounded-md text-sm"
                >
                  <option value="customer">{t?.customerLabel ?? 'عميل'}</option>
                  <option value="supplier">{t?.supplierLabel ?? 'مورد'}</option>
                </select>
                <select
                  value={selectedPartyId}
                  onChange={(e) => setSelectedPartyId(e.target.value)}
                  className="flex-1 px-3 py-2 border rounded-md text-sm"
                >
                  <option value="">{t?.selectParty ?? 'اختر الجهة...'}</option>
                  {(selectedPartyType === 'customer' ? customers : suppliers).map((party) => (
                    <option key={party.id} value={party.id}>
                      {party.name}
                    </option>
                  ))}
                </select>
              </div>
            </div>

            <div className="space-y-2">
              <Label>{t?.endorsementReference ?? 'مرجع الفاتورة/السند'}</Label>
              <Input
                placeholder={t?.endorsementReferencePlaceholder ?? 'مثال: PO/2026/0042 أو INV-552'}
                value={endorsementReference}
                onChange={(e) => setEndorsementReference(e.target.value)}
              />
            </div>

            <div className="space-y-2">
              <Label>{t?.notes ?? 'ملاحظات'}</Label>
              <Textarea
                placeholder={t?.notesPlaceholder ?? 'أدخل ملاحظات التجيير...'}
                value={notes}
                onChange={(e) => setNotes(e.target.value)}
                rows={3}
              />
            </div>

            <DialogFooter>
              <Button variant="outline" onClick={() => onOpenChange(false)}>
                {t?.cancel ?? 'إلغاء'}
              </Button>
              <Button onClick={handleEndorseToParty} disabled={!selectedParty || isSubmitting || isEditLocked}>
                {isSubmitting ? (t?.processing ?? 'جاري المعالجة...') : (t?.endorse ?? 'تجيير')}
              </Button>
            </DialogFooter>
          </TabsContent>

          <TabsContent value="collection" className="space-y-4">
            <div className="bg-blue-50 dark:bg-blue-950 p-3 rounded-md">
              <p className="text-sm text-blue-800 dark:text-blue-200">
                {t?.transferToCollectionDescription ?? 'انقل هذا الشيك إلى حساب التحصيل. سيتم إنشاء قيد محاسبي لمتابعة الشيك ضمن التحصيل.'}
              </p>
              <div className="mt-3 flex flex-wrap gap-2">
                <Button variant="outline" size="sm" asChild>
                  <Link href="/admin/accounting/chart?focus=1015">
                    {t?.createIncomingChecksAccount ?? 'إنشاء حساب 1015 - شيكات واردة'}
                  </Link>
                </Button>
                <Button variant="outline" size="sm" asChild>
                  <Link href="/admin/accounting/chart?focus=1020">
                    {t?.createCollectionChecksAccount ?? 'إنشاء حساب 1020 - شيكات برسم التحصيل'}
                  </Link>
                </Button>
              </div>
              {!collectionAccountsReady && (
                <p className="mt-2 text-xs text-amber-700 dark:text-amber-300">
                  {t?.collectionAccountsMissing ?? 'حسابات التحصيل غير جاهزة. أنشئ الحسابين 1015 و1020 أولاً ثم أعد المحاولة.'}
                </p>
              )}
            </div>

            <div className="space-y-2">
              <Label>{t?.notes ?? 'ملاحظات'}</Label>
              <Textarea
                placeholder={t?.notesPlaceholder ?? 'أدخل ملاحظات التحويل...'}
                value={notes}
                onChange={(e) => setNotes(e.target.value)}
                rows={3}
              />
            </div>

            <DialogFooter>
              <Button variant="outline" onClick={() => onOpenChange(false)}>
                {t?.cancel ?? 'إلغاء'}
              </Button>
              <Button onClick={handleTransferToCollection} disabled={isSubmitting || isEditLocked || !collectionAccountsReady}>
                {isSubmitting ? (t?.processing ?? 'جاري المعالجة...') : (t?.transfer ?? 'تحويل')}
              </Button>
            </DialogFooter>
          </TabsContent>
        </Tabs>
      </DialogContent>
    </Dialog>
  );
}
