'use client';

import { useMemo, useState, useEffect } from 'react';
import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { Check, ChevronsUpDown, AlertTriangle } from 'lucide-react';
import type { SalesInvoice } from '@/lib/modules/sales';
import type { ProductionItem } from '@/lib/types';
import { formatDateStable } from '@/lib/formatters';
import { handleCreateSalesReturn, handleGetSalesReturnsByInvoice } from '@/lib/actions/sales-return.actions';
import { useToast } from '@/hooks/use-toast';
import { cn } from '@/lib/utils';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Textarea } from '@/components/ui/textarea';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';

type SalesReturnsClientProps = {
  invoices: SalesInvoice[];
  materials: ProductionItem[];
  userId: string;
  userName: string;
};

type ReturnItem = {
  lineId: string;
  materialId: string;
  name: string;
  originalQuantity: number;
  returnedQuantity: number;
  unitPrice: number;
  condition: 'good' | 'damaged' | 'defective' | 'faulty';
  conditionNotes?: string;
};

type ReturnReason = 'defective' | 'wrong_item' | 'customer_request' | 'quality_issue' | 'damaged' | 'other';

const RETURN_REASONS = {
  defective: 'معيب أو غير صالح',
  wrong_item: 'منتج خاطئ',
  customer_request: 'طلب من العميل',
  quality_issue: 'مشكلة في الجودة',
  damaged: 'معطوب/ تالف',
  other: 'آخر',
} as const;

export default function SalesReturnsClient({
  invoices,
  materials,
  userId,
  userName,
}: SalesReturnsClientProps) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { toast } = useToast();
  const [invoicePickerOpen, setInvoicePickerOpen] = useState(false);
  const [invoiceSearchQuery, setInvoiceSearchQuery] = useState('');
  const [selectedInvoiceId, setSelectedInvoiceId] = useState(() => searchParams.get('invoiceId') ?? '');
  const [selectedReason, setSelectedReason] = useState<ReturnReason>('defective');
  const [reasonDescription, setReasonDescription] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [existingReturns, setExistingReturns] = useState<{ returnNumber: string; status: string }[]>([]);
  const [checkingReturns, setCheckingReturns] = useState(false);
  const [returnItems, setReturnItems] = useState<ReturnItem[]>(() => {
    const preselectedId = searchParams.get('invoiceId');
    if (preselectedId) {
      const invoice = invoices.find((inv) => inv.id === preselectedId);
      if (invoice) {
        return invoice.items.map((item, idx) => ({
          lineId: `line-${idx}`,
          materialId: item.materialId,
          name: item.name,
          originalQuantity: item.quantity,
          returnedQuantity: 0,
          unitPrice: item.unitPrice,
          condition: 'good' as const,
          conditionNotes: '',
        }));
      }
    }
    return [];
  });

  const activeInvoices = useMemo(
    () => invoices.filter((invoice) => invoice.status === 'active'),
    [invoices]
  );

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

  const materialsById = useMemo(() => {
    return new Map(materials.map((material) => [String(material.id || '').trim(), material]));
  }, [materials]);

  const searchableInvoices = useMemo(() => {
    const normalizedQuery = invoiceSearchQuery.trim().toLowerCase();
    const entries = activeInvoices.map((invoice) => {
      const itemNames = (invoice.items || [])
        .map((item) => String(item.name || '').trim())
        .filter(Boolean)
        .join(' | ');

      const itemSearchIndex = (invoice.items || [])
        .flatMap((item) => {
          const rawItem = item as any;
          const material = materialsById.get(String(item.materialId || '').trim());
          const rawMaterial = material as any;
          const additionalBarcodes = [
            ...(Array.isArray(rawItem.additionalBarcodes) ? rawItem.additionalBarcodes : []),
            ...(Array.isArray(material?.additionalBarcodes) ? material!.additionalBarcodes : []),
          ]
            .map((value: unknown) => String(value || '').trim())
            .filter(Boolean);

          const secondaryUnitBarcodes = Array.isArray(material?.secondaryUnits)
            ? material!.secondaryUnits.map((entry) => String(entry?.barcode || '').trim())
            : [];

          return [
            item.materialId,
            item.name,
            item.description,
            item.serialNumber,
            item.rfidCode,
            rawItem.barcode,
            rawItem.itemNumber,
            material?.name,
            material?.itemNumber,
            material?.barcode,
            material?.secondaryBarcode,
            rawMaterial?.globalReferenceNumber,
            rawMaterial?.itemSymbolName,
            ...additionalBarcodes,
            ...secondaryUnitBarcodes,
          ];
        })
        .map((value) => String(value || '').trim())
        .filter(Boolean)
        .join(' ');

      const searchableText = [
        invoice.id,
        invoice.invoiceNumber,
        invoice.manualDocNumber,
        invoice.customerId,
        invoice.customerName,
        itemNames,
        itemSearchIndex,
      ]
        .join(' ')
        .toLowerCase();

      return {
        invoice,
        itemNames,
        searchableText,
      };
    });

    if (!normalizedQuery) {
      return entries;
    }

    return entries.filter((entry) => entry.searchableText.includes(normalizedQuery));
  }, [activeInvoices, invoiceSearchQuery, materialsById]);

  // Check for existing returns when invoice is selected
  useEffect(() => {
    if (!selectedInvoiceId) {
      setExistingReturns([]);
      return;
    }
    let cancelled = false;
    setCheckingReturns(true);
    handleGetSalesReturnsByInvoice(selectedInvoiceId).then((result) => {
      if (cancelled) return;
      if (result.success && result.data && result.data.length > 0) {
        setExistingReturns(
          result.data.map((r: any) => ({ returnNumber: r.returnNumber || r.id, status: r.status }))
        );
      } else {
        setExistingReturns([]);
      }
      setCheckingReturns(false);
    });
    return () => { cancelled = true; };
  }, [selectedInvoiceId]);

  // Initialize return items when invoice is selected
  const handleInvoiceSelect = (invoiceId: string) => {
    setSelectedInvoiceId(invoiceId);
    setInvoicePickerOpen(false);
    setInvoiceSearchQuery('');
    const invoice = invoices.find((inv) => inv.id === invoiceId);
    if (invoice) {
      setReturnItems(
        invoice.items.map((item, idx) => ({
          lineId: `line-${idx}`,
          materialId: item.materialId,
          name: item.name,
          originalQuantity: item.quantity,
          returnedQuantity: 0,
          unitPrice: item.unitPrice,
          condition: 'good' as const,
          conditionNotes: '',
        }))
      );
    }
  };

  // Update returned quantity for an item
  const handleItemQuantityChange = (lineId: string, quantity: number) => {
    setReturnItems((items) =>
      items.map((item) =>
        item.lineId === lineId
          ? { ...item, returnedQuantity: Math.min(quantity, item.originalQuantity) }
          : item
      )
    );
  };

  // Update condition for an item
  const handleItemConditionChange = (
    lineId: string,
    condition: 'good' | 'damaged' | 'defective' | 'faulty'
  ) => {
    setReturnItems((items) =>
      items.map((item) =>
        item.lineId === lineId ? { ...item, condition } : item
      )
    );
  };

  // Calculate return totals
  const returnTotals = useMemo(() => {
    const subTotal = returnItems.reduce(
      (sum, item) => sum + item.returnedQuantity * item.unitPrice,
      0
    );
    return {
      subTotal,
      taxAmount: 0, // TODO: Calculate based on tax method
      totalAmount: subTotal,
      itemCount: returnItems.filter((i) => i.returnedQuantity > 0).length,
    };
  }, [returnItems]);

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

    const itemsToReturn = returnItems.filter((i) => i.returnedQuantity > 0);
    if (itemsToReturn.length === 0) {
      toast({
        title: 'خطأ',
        description: 'يرجى تحديد الكميات المراد مردها.',
        variant: 'destructive',
      });
      return;
    }

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

    try {
      setIsSubmitting(true);
      const result = await handleCreateSalesReturn(
        selectedInvoiceId,
        itemsToReturn.map((item) => ({
          lineId: item.lineId,
          materialId: item.materialId,
          returnedQuantity: item.returnedQuantity,
          condition: item.condition,
          conditionNotes: item.conditionNotes,
        })),
        selectedReason,
        reasonDescription,
        userId,
        userName
      );

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

      toast({
        title: 'تم تسجيل المردود بنجاح',
        description: `تم تسجيل مردود #${result.data?.returnNumber}`,
      });
      
      // Reset form
      setSelectedInvoiceId('');
      setReturnItems([]);
      setReasonDescription('');
      setSelectedReason('defective');
      router.refresh();
    } catch (error) {
      toast({
        title: 'خطأ',
        description: 'حدث خطأ غير متوقع أثناء تسجيل المردود.',
        variant: 'destructive',
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="space-y-4">
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between gap-2">
            <CardTitle>تسجيل مردود مبيعات (كامل أو جزئي)</CardTitle>
            <Button asChild variant="outline" size="sm">
              <Link href="/admin/sales/returns/list">قائمة فواتير مردود المبيعات</Link>
            </Button>
          </div>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
            <div className="rounded-md border p-4">
              <p className="text-sm text-muted-foreground">فواتير نشطة</p>
              <p className="text-2xl font-bold">{activeInvoices.length}</p>
            </div>
            <div className="rounded-md border p-4">
              <p className="text-sm text-muted-foreground">بنود المردود</p>
              <p className="text-2xl font-bold">{returnTotals.itemCount}</p>
            </div>
            <div className="rounded-md border p-4">
              <p className="text-sm text-muted-foreground">إجمالي المردود</p>
              <p className="text-2xl font-bold">{returnTotals.totalAmount.toFixed(2)}</p>
            </div>
            <div className="rounded-md border p-4 text-sm text-muted-foreground">
              يدعم المردودات الجزئية والكاملة مع تتبع حالات متعددة.
            </div>
          </div>

          {/* Invoice Selection */}
          <div className="space-y-2">
            <label className="text-sm font-medium">الفاتورة</label>
            <Popover open={invoicePickerOpen} onOpenChange={setInvoicePickerOpen}>
              <PopoverTrigger asChild>
                <Button
                  type="button"
                  variant="outline"
                  role="combobox"
                  aria-expanded={invoicePickerOpen}
                  className="w-full justify-between"
                >
                  {selectedInvoice ? (
                    <span className="truncate text-right">
                      {selectedInvoice.invoiceNumber} | {selectedInvoice.customerName} | {selectedInvoice.grandTotal.toFixed(2)}
                    </span>
                  ) : (
                    <span className="text-muted-foreground">اختر فاتورة نشطة</span>
                  )}
                  <ChevronsUpDown className="h-4 w-4 shrink-0 opacity-50" />
                </Button>
              </PopoverTrigger>
              <PopoverContent className="w-[var(--radix-popover-trigger-width)] p-0" align="start">
                <div className="border-b p-2">
                  <Input
                    value={invoiceSearchQuery}
                    onChange={(event) => setInvoiceSearchQuery(event.target.value)}
                    placeholder="ابحث بالفاتورة، الزبون، الصنف، الباركود، الرقم التسلسلي، أو RFID"
                    className="h-9"
                  />
                </div>
                <ScrollArea className="max-h-72">
                  <div className="p-1">
                    {searchableInvoices.length === 0 ? (
                      <div className="px-2 py-6 text-center text-sm text-muted-foreground">
                        لا توجد نتائج مطابقة.
                      </div>
                    ) : (
                      searchableInvoices.map(({ invoice, itemNames }) => (
                        <button
                          key={invoice.id}
                          type="button"
                          onClick={() => handleInvoiceSelect(invoice.id)}
                          className="flex w-full items-start gap-2 rounded-sm px-2 py-2 text-right hover:bg-accent hover:text-accent-foreground"
                        >
                          <Check
                            className={cn(
                              'mt-0.5 h-4 w-4 shrink-0',
                              selectedInvoiceId === invoice.id ? 'opacity-100' : 'opacity-0'
                            )}
                          />
                          <div className="min-w-0 flex-1">
                            <div className="truncate text-sm font-medium">
                              {invoice.invoiceNumber} | {invoice.customerName} | {invoice.grandTotal.toFixed(2)}
                            </div>
                            {itemNames ? (
                              <div className="truncate text-xs text-muted-foreground">
                                أصناف: {itemNames}
                              </div>
                            ) : null}
                          </div>
                        </button>
                      ))
                    )}
                  </div>
                </ScrollArea>
              </PopoverContent>
            </Popover>
          </div>

          {/* Duplicate return warning */}
          {existingReturns.length > 0 && (
            <div className="flex items-start gap-3 rounded-md border border-amber-400 bg-amber-50 p-4 text-amber-900 dark:bg-amber-950 dark:text-amber-200">
              <AlertTriangle className="mt-0.5 h-5 w-5 shrink-0 text-amber-500" />
              <div className="text-sm">
                <p className="font-semibold mb-1">تحذير: يوجد مردود مسبق لهذه الفاتورة</p>
                <ul className="list-disc list-inside space-y-0.5">
                  {existingReturns.map((r) => (
                    <li key={r.returnNumber}>
                      <span className="font-medium">{r.returnNumber}</span>
                      {' — '}
                      <span>{r.status}</span>
                    </li>
                  ))}
                </ul>
                <p className="mt-1 text-xs text-amber-700 dark:text-amber-400">تأكد أنك لا تسجل مردوداً مكرراً لنفس الفاتورة.</p>
              </div>
            </div>
          )}

          {/* Return Items */}
          {selectedInvoice && returnItems.length > 0 && (
            <>
              <div className="border rounded-lg p-4">
                <h3 className="font-semibold mb-4">بنود المردود</h3>
                <div className="overflow-x-auto">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>المنتج</TableHead>
                        <TableHead>الكمية الأصلية</TableHead>
                        <TableHead>الكمية المردودة</TableHead>
                        <TableHead>السعر</TableHead>
                        <TableHead>الحالة</TableHead>
                        <TableHead>ملاحظات</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {returnItems.map((item) => (
                        <TableRow key={item.lineId}>
                          <TableCell className="font-medium">{item.name}</TableCell>
                          <TableCell>{item.originalQuantity}</TableCell>
                          <TableCell>
                            <Input
                              type="number"
                              min="0"
                              max={item.originalQuantity}
                              value={item.returnedQuantity}
                              onChange={(e) =>
                                handleItemQuantityChange(
                                  item.lineId,
                                  parseInt(e.target.value, 10) || 0
                                )
                              }
                              className="w-20"
                            />
                          </TableCell>
                          <TableCell>{item.unitPrice.toFixed(2)}</TableCell>
                          <TableCell>
                            <Select
                              value={item.condition}
                              onValueChange={(val) =>
                                handleItemConditionChange(
                                  item.lineId,
                                  val as 'good' | 'damaged' | 'defective' | 'faulty'
                                )
                              }
                            >
                              <SelectTrigger className="w-32">
                                <SelectValue />
                              </SelectTrigger>
                              <SelectContent>
                                <SelectItem value="good">سليم</SelectItem>
                                <SelectItem value="damaged">معطوب</SelectItem>
                                <SelectItem value="defective">معيب</SelectItem>
                                <SelectItem value="faulty">خاطئ</SelectItem>
                              </SelectContent>
                            </Select>
                          </TableCell>
                          <TableCell>
                            <Input
                              type="text"
                              placeholder="ملاحظات"
                              value={item.conditionNotes || ''}
                              onChange={(e) => {
                                setReturnItems((items) =>
                                  items.map((i) =>
                                    i.lineId === item.lineId
                                      ? { ...i, conditionNotes: e.target.value }
                                      : i
                                  )
                                );
                              }}
                              className="w-32"
                            />
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </div>
              </div>

              {/* Return Reason */}
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <label className="text-sm font-medium">سبب المردود الرئيسي</label>
                  <Select value={selectedReason} onValueChange={(val) => setSelectedReason(val as ReturnReason)}>
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      {Object.entries(RETURN_REASONS).map(([key, label]) => (
                        <SelectItem key={key} value={key}>
                          {label}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-2">
                  <label className="text-sm font-medium">وصف السبب (مفصل)</label>
                  <Textarea
                    value={reasonDescription}
                    onChange={(e) => setReasonDescription(e.target.value)}
                    placeholder="اشرح بالتفصيل سبب المردود"
                    rows={2}
                  />
                </div>
              </div>

              {/* Action Buttons */}
              <div className="flex justify-end gap-2">
                <Button variant="outline" onClick={() => setSelectedInvoiceId('')}>
                  إلغاء
                </Button>
                <Button
                  disabled={
                    isSubmitting ||
                    returnTotals.itemCount === 0
                  }
                  onClick={onRegisterReturn}
                >
                  {isSubmitting ? 'جاري التنفيذ...' : 'تسجيل المردود'}
                </Button>
              </div>
            </>
          )}
        </CardContent>
      </Card>

    </div>
  );
}
