'use client';

import { useMemo, useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import type { SalesInvoice } from '@/lib/modules/sales';
import { handleIssueSalesDebitNote } from '@/lib/actions/sales-invoice.actions';
import { formatDateDDMMYYYY } from '@/lib/utils';
import { useDocumentLock } from '@/hooks/use-document-lock';
import { useToast } from '@/hooks/use-toast';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { PartySelector } from '@/components/invoice-shared/party-selector';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';

type SalesDebitNotesClientProps = {
  invoices: SalesInvoice[];
  userId: string;
  userName: string;
};

export default function SalesDebitNotesClient({
  invoices,
  userId,
  userName,
}: SalesDebitNotesClientProps) {
  const router = useRouter();
  const { toast } = useToast();
  const [selectedInvoiceId, setSelectedInvoiceId] = useState('');
  const [amount, setAmount] = useState('');
  const [reason, setReason] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);

  const selectedInvoice = useMemo(
    () => invoices.find((invoice) => invoice.id === selectedInvoiceId) || null,
    [invoices, selectedInvoiceId]
  );

  const maxDebitAmount = Number(selectedInvoice?.grandTotal || 0);
  const selectedSecondaryPercent = Math.max(0, Math.min(100, Number((selectedInvoice as any)?.secondaryCoveragePercent || 0)));
  const hasSelectedSecondaryCoverage = Boolean(String((selectedInvoice as any)?.secondaryCustomerId || '').trim()) && selectedSecondaryPercent > 0;
  const selectedSecondaryAmount = hasSelectedSecondaryCoverage
    ? (Number((selectedInvoice as any)?.secondaryCoverageAmount || 0) > 0
      ? Number((selectedInvoice as any)?.secondaryCoverageAmount || 0)
      : Number(((maxDebitAmount * selectedSecondaryPercent) / 100).toFixed(2)))
    : 0;
  const selectedPrimaryAmount = Number((maxDebitAmount - selectedSecondaryAmount).toFixed(2));
  const parsedDebitAmount = Number(amount);
  const hasValidDebitAmount = Number.isFinite(parsedDebitAmount) && parsedDebitAmount > 0;
  const debitSecondaryAmount = hasSelectedSecondaryCoverage && hasValidDebitAmount
    ? Number(((parsedDebitAmount * selectedSecondaryPercent) / 100).toFixed(2))
    : 0;
  const debitPrimaryAmount = hasValidDebitAmount
    ? Number((parsedDebitAmount - debitSecondaryAmount).toFixed(2))
    : 0;
  const { lockStatus, isAcquiring } = useDocumentLock('sales_invoice_debit_note', selectedInvoiceId, {
    enabled: Boolean(selectedInvoiceId),
  });

  const eligibleInvoices = useMemo(
    () => invoices.filter((invoice) => invoice.status !== 'cancelled'),
    [invoices]
  );

  const invoiceOptions = useMemo(
    () => eligibleInvoices.map((invoice) => ({
      id: invoice.id,
      label: `${invoice.invoiceNumber} | ${invoice.customerName}`,
      description: `${formatDateDDMMYYYY(invoice.date)} | ${Number(invoice.grandTotal || 0).toFixed(2)}`,
      searchableText: [
        invoice.invoiceNumber,
        invoice.customerName,
        String((invoice as any).secondaryCustomerName || ''),
        formatDateDDMMYYYY(invoice.date),
      ].join(' '),
    })),
    [eligibleInvoices]
  );

  const withDiscount = useMemo(
    () => invoices.filter((invoice) => (invoice.totalDiscount || 0) > 0),
    [invoices]
  );
  const totalAdjustments = withDiscount.reduce(
    (sum, invoice) => sum + (invoice.totalDiscount || 0),
    0
  );

  const issuedDebitNotes = useMemo(() => {
    const collected: Array<{
      key: string;
      invoiceId: string;
      invoiceNumber: string;
      customerName: string;
      amount: number;
      reason: string;
      createdAt: string;
      createdBy: string;
    }> = [];

    for (const invoice of invoices) {
      const invoiceId = String(invoice.id || '').trim();
      if (!invoiceId) continue;

      const logEntries = Array.isArray((invoice as any).activityLog) ? (invoice as any).activityLog : [];
      for (const entry of logEntries) {
        const message = String(entry?.message || '').trim();
        const match = message.match(/^Debit note issued \(([0-9.]+)\):\s*(.+)$/i);
        if (!match) continue;

        const amountValue = Number(match[1] || 0);
        const reasonValue = String(match[2] || '').trim();
        const createdAt = String(entry?.timestamp || '').trim() || new Date(0).toISOString();
        const createdBy = String(entry?.byName || entry?.by || '-').trim() || '-';
        const key = `${invoiceId}::${createdAt}::${amountValue.toFixed(2)}::${reasonValue}`;

        collected.push({
          key,
          invoiceId,
          invoiceNumber: String(invoice.invoiceNumber || invoiceId),
          customerName: String(invoice.customerName || '-'),
          amount: Number.isFinite(amountValue) ? amountValue : 0,
          reason: reasonValue || '-',
          createdAt,
          createdBy,
        });
      }

      const internalNotes = String((invoice as any).internalNotes || '');
      const noteLines = internalNotes.split('\n').map((line) => line.trim()).filter(Boolean);
      for (const noteLine of noteLines) {
        const noteMatch = noteLine.match(/^\[DEBIT_NOTE\s+([^\]]+)\]\s+[+-]([0-9.]+)\s+\|\s*(.+)$/i);
        if (!noteMatch) continue;

        const createdAt = String(noteMatch[1] || '').trim() || new Date(0).toISOString();
        const amountValue = Number(noteMatch[2] || 0);
        const reasonValue = String(noteMatch[3] || '').trim();
        const key = `${invoiceId}::${createdAt}::${amountValue.toFixed(2)}::${reasonValue}`;

        collected.push({
          key,
          invoiceId,
          invoiceNumber: String(invoice.invoiceNumber || invoiceId),
          customerName: String(invoice.customerName || '-'),
          amount: Number.isFinite(amountValue) ? amountValue : 0,
          reason: reasonValue || '-',
          createdAt,
          createdBy: '-',
        });
      }
    }

    const deduped = Array.from(new Map(collected.map((item) => [item.key, item])).values());
    deduped.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
    return deduped;
  }, [invoices]);

  const onIssueDebitNote = async () => {
    if (!selectedInvoiceId) {
      toast({ title: 'خطأ', description: 'يرجى اختيار فاتورة.', variant: 'destructive' });
      return;
    }

    const parsedAmount = Number(amount);
    if (!Number.isFinite(parsedAmount) || parsedAmount <= 0) {
      toast({
        title: 'خطأ',
        description: 'يرجى إدخال مبلغ صحيح أكبر من صفر.',
        variant: 'destructive',
      });
      return;
    }

    if (selectedInvoice && parsedAmount - maxDebitAmount > 0.01) {
      toast({
        title: 'خطأ',
        description: `لا يمكن أن يتجاوز مبلغ إشعار التخفيض قيمة الفاتورة (${maxDebitAmount.toFixed(2)}).`,
        variant: 'destructive',
      });
      return;
    }

    if (lockStatus.isLocked) {
      toast({
        title: 'الفاتورة قيد الاستخدام',
        description: lockStatus.lockedBy?.userName
          ? `هذه الفاتورة قيد الاستخدام بواسطة ${lockStatus.lockedBy.userName}.`
          : 'هذه الفاتورة قيد الاستخدام بواسطة مستخدم آخر.',
        variant: 'destructive',
      });
      return;
    }

    if (!reason.trim()) {
      toast({
        title: 'خطأ',
        description: 'يرجى إدخال سبب إصدار إشعار التخفيض.',
        variant: 'destructive',
      });
      return;
    }

    try {
      setIsSubmitting(true);
      const result = await handleIssueSalesDebitNote(
        selectedInvoiceId,
        parsedAmount,
        reason.trim(),
        userId,
        userName
      );

      if (!result.success) {
        toast({
          title: 'تعذر إصدار إشعار تخفيض',
          description: result.error || 'حدث خطأ غير متوقع.',
          variant: 'destructive',
        });
        return;
      }

      toast({
        title: 'تم إصدار إشعار تخفيض',
        description: `تم تخفيض ${parsedAmount.toFixed(2)} من الفاتورة ${result.data?.invoiceNumber}.`,
      });
      setSelectedInvoiceId('');
      setAmount('');
      setReason('');
      router.refresh();
    } catch {
      toast({
        title: 'تعذر إصدار إشعار تخفيض',
        description: 'حدث خطأ غير متوقع أثناء التنفيذ.',
        variant: 'destructive',
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="space-y-4">
      <Tabs defaultValue="issue" className="w-full">
        <TabsList className="flex w-full flex-wrap justify-start h-auto bg-muted p-1 gap-1">
          <TabsTrigger value="issue" className="text-xs sm:text-sm h-auto whitespace-normal leading-tight">إصدار إشعار تخفيض</TabsTrigger>
          <TabsTrigger value="issued-notes" className="text-xs sm:text-sm h-auto whitespace-normal leading-tight">السندات الصادرة</TabsTrigger>
          <TabsTrigger value="discount-summary" className="text-xs sm:text-sm h-auto whitespace-normal leading-tight">ملخص الفواتير ذات الخصم</TabsTrigger>
        </TabsList>

        <TabsContent value="issue" className="mt-4">
          <Card>
            <CardHeader>
              <CardTitle>إصدار إشعار تخفيض</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div className="rounded-md border p-4">
              <p className="text-sm text-muted-foreground">فواتير بها خصم</p>
              <p className="text-2xl font-bold">{withDiscount.length}</p>
            </div>
            <div className="rounded-md border p-4">
              <p className="text-sm text-muted-foreground">إجمالي التخفيضات الحالية</p>
              <p className="text-2xl font-bold">{totalAdjustments.toFixed(2)}</p>
            </div>
            <div className="rounded-md border p-4 text-sm text-muted-foreground">
              الإشعار هنا يُستخدم كتخفيض: يتم إنقاص إجمالي الفاتورة والرصيد المستحق مع تتبع النشاط في السجل.
            </div>
          </div>

          <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
            <div className="space-y-2">
              <label className="text-sm font-medium">الفاتورة</label>
              <PartySelector
                value={selectedInvoiceId}
                options={invoiceOptions}
                placeholder="اختر فاتورة"
                searchPlaceholder="ابحث برقم الفاتورة أو اسم العميل"
                emptyLabel="لا توجد فواتير مطابقة"
                onValueChange={setSelectedInvoiceId}
              />
            </div>

            {selectedInvoice && (
              <div className="rounded-md border p-3 text-sm lg:col-span-2">
                <div className="grid grid-cols-1 md:grid-cols-3 gap-2">
                  <div>
                    <p className="text-muted-foreground">رقم الفاتورة</p>
                    <p className="font-medium">{selectedInvoice.invoiceNumber}</p>
                  </div>
                  <div>
                    <p className="text-muted-foreground">العميل</p>
                    <p className="font-medium">{selectedInvoice.customerName}</p>
                  </div>
                  <div>
                    <p className="text-muted-foreground">التاريخ</p>
                    <p className="font-medium">{formatDateDDMMYYYY(selectedInvoice.date)}</p>
                  </div>
                  <div>
                    <p className="text-muted-foreground">إجمالي الفاتورة</p>
                    <p className="font-semibold">{Number(selectedInvoice.grandTotal || 0).toFixed(2)}</p>
                  </div>
                  <div>
                    <p className="text-muted-foreground">المدفوع</p>
                    <p className="font-medium">{Number(selectedInvoice.amountReceived || 0).toFixed(2)}</p>
                  </div>
                  <div>
                    <p className="text-muted-foreground">المتبقي</p>
                    <p className="font-medium">{Number(selectedInvoice.amountDue || 0).toFixed(2)}</p>
                  </div>
                </div>
                <p className="mt-2 text-xs text-muted-foreground">
                  الحد الأقصى لمبلغ إشعار التخفيض لهذه الفاتورة: {maxDebitAmount.toFixed(2)}
                </p>
                {hasSelectedSecondaryCoverage && (
                  <div className="mt-2 grid grid-cols-1 md:grid-cols-2 gap-2 text-xs">
                    <div className="rounded bg-muted/40 px-2 py-1">
                      <span className="font-medium">الذمة الرئيسية:</span>{' '}
                      {(100 - selectedSecondaryPercent).toFixed(2)}% ({selectedPrimaryAmount.toFixed(2)})
                    </div>
                    <div className="rounded bg-muted/40 px-2 py-1">
                      <span className="font-medium">الذمة الفرعية:</span>{' '}
                      {selectedSecondaryPercent.toFixed(2)}% ({selectedSecondaryAmount.toFixed(2)})
                    </div>
                  </div>
                )}
                {lockStatus.isLocked && lockStatus.showLockMessage !== false && (
                  <p className="mt-2 text-xs text-destructive">
                    هذه الفاتورة قيد الاستخدام بواسطة {lockStatus.lockedBy?.userName || 'مستخدم آخر'}، لا يمكن إصدار إشعار تخفيض الآن.
                  </p>
                )}
              </div>
            )}

            <div className="space-y-2">
              <label className="text-sm font-medium">مبلغ إشعار التخفيض</label>
              <Input
                type="number"
                min="0"
                step="0.01"
                max={selectedInvoice ? maxDebitAmount : undefined}
                value={amount}
                onChange={(event) => setAmount(event.target.value)}
                placeholder="0.00"
                disabled={lockStatus.isLocked || isAcquiring}
              />
              {hasSelectedSecondaryCoverage && (
                <div className="rounded-md border border-amber-200/70 bg-amber-50/60 px-3 py-2 text-sm leading-6">
                  <p className="font-medium text-amber-900">
                    يتم توزيع مبلغ الإشعار تلقائيا حسب نسب التغطية.
                  </p>
                  {hasValidDebitAmount && (
                    <div className="mt-2 flex flex-wrap items-center gap-2 text-xs">
                      <span className="rounded bg-emerald-100 px-2 py-0.5 font-semibold text-emerald-800">
                        رئيسية: {debitPrimaryAmount.toFixed(2)}
                      </span>
                      <span className="rounded bg-sky-100 px-2 py-0.5 font-semibold text-sky-800">
                        فرعية: {debitSecondaryAmount.toFixed(2)}
                      </span>
                    </div>
                  )}
                </div>
              )}
            </div>

            <div className="space-y-2 lg:col-span-3">
              <label className="text-sm font-medium">السبب</label>
              <Textarea
                value={reason}
                onChange={(event) => setReason(event.target.value)}
                placeholder="اكتب سبب إصدار إشعار التخفيض"
                rows={3}
                disabled={lockStatus.isLocked || isAcquiring}
              />
            </div>
          </div>

          <div className="flex justify-end">
            <Button disabled={isSubmitting || isAcquiring || lockStatus.isLocked || eligibleInvoices.length === 0} onClick={onIssueDebitNote}>
              {isSubmitting ? 'جاري الإصدار...' : 'إصدار إشعار تخفيض'}
            </Button>
          </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="issued-notes" className="mt-4">
          <Card>
            <CardHeader>
              <CardTitle>السندات الصادرة</CardTitle>
              <p className="text-sm text-muted-foreground">
                يتم حفظ السند ضمن الفاتورة نفسها في السجل والنص الداخلي، ويظهر هنا بعد الإنشاء مباشرة.
              </p>
            </CardHeader>
            <CardContent>
              <div className="rounded-md border overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>التاريخ</TableHead>
                      <TableHead>الفاتورة</TableHead>
                      <TableHead>العميل</TableHead>
                      <TableHead>مبلغ السند</TableHead>
                      <TableHead>السبب</TableHead>
                      <TableHead>بواسطة</TableHead>
                      <TableHead>إجراء</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {issuedDebitNotes.length === 0 ? (
                      <TableRow>
                        <TableCell colSpan={7} className="text-center text-muted-foreground py-8">
                          لا توجد سندات صادرة حتى الآن.
                        </TableCell>
                      </TableRow>
                    ) : (
                      issuedDebitNotes.map((note) => (
                        <TableRow key={note.key}>
                          <TableCell>{String(note.createdAt || '').slice(0, 19).replace('T', ' ')}</TableCell>
                          <TableCell className="font-medium">{note.invoiceNumber}</TableCell>
                          <TableCell>{note.customerName}</TableCell>
                          <TableCell className="font-semibold text-rose-700">{note.amount.toFixed(2)}</TableCell>
                          <TableCell>{note.reason}</TableCell>
                          <TableCell>{note.createdBy}</TableCell>
                          <TableCell>
                            <Button asChild variant="outline" size="sm">
                              <Link href={`/admin/sales/view/${note.invoiceId}`}>عرض الفاتورة</Link>
                            </Button>
                          </TableCell>
                        </TableRow>
                      ))
                    )}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="discount-summary" className="mt-4">
          <Card>
            <CardHeader>
              <CardTitle>ملخص الفواتير ذات الخصم</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="rounded-md border overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>الفاتورة</TableHead>
                      <TableHead>العميل</TableHead>
                      <TableHead>الإجمالي قبل الخصم</TableHead>
                      <TableHead>إجمالي الخصم</TableHead>
                      <TableHead>الإجمالي النهائي</TableHead>
                      <TableHead>إجراء</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {withDiscount.length === 0 ? (
                      <TableRow>
                        <TableCell colSpan={6} className="text-center text-muted-foreground py-8">
                          لا توجد فواتير تحتوي على تخفيضات.
                        </TableCell>
                      </TableRow>
                    ) : (
                      withDiscount.map((invoice) => (
                        <TableRow key={invoice.id}>
                          <TableCell className="font-medium">{invoice.invoiceNumber}</TableCell>
                          <TableCell>{invoice.customerName}</TableCell>
                          <TableCell>{invoice.subTotal.toFixed(2)}</TableCell>
                          <TableCell className="text-amber-700 font-semibold">
                            {(invoice.totalDiscount || 0).toFixed(2)}
                          </TableCell>
                          <TableCell>{invoice.grandTotal.toFixed(2)}</TableCell>
                          <TableCell>
                            <Button asChild variant="outline" size="sm">
                              <Link href={`/admin/sales/view/${invoice.id}`}>عرض</Link>
                            </Button>
                          </TableCell>
                        </TableRow>
                      ))
                    )}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}
