/**
 * Sales Invoice History (Placeholder)
 * Display list of sales invoices
 */

'use client';

import Link from 'next/link';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import { useMemo, useState, type MouseEvent } from 'react';
import { formatDateStable } from '@/lib/formatters';
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { ArrowUpDown, MoreHorizontal, X } from 'lucide-react';
import type { SalesInvoice } from '@/lib/modules/sales';

interface SalesInvoiceHistoryProps {
  invoices: SalesInvoice[];
  total: number;
  pageSize: number;
  currentPage: number;
  search?: string;
  status?: string;
  documentType?: string;
  currencySymbol?: string;
}

type SortKey = 'invoiceNumber' | 'documentType' | 'customerName' | 'secondaryCustomerName' | 'date' | 'grandTotal' | 'coverage' | 'status' | 'linking';
type SortDirection = 'asc' | 'desc';

export default function SalesInvoiceHistory({
  invoices,
  total,
  pageSize,
  currentPage,
  search,
  status,
  documentType,
  currencySymbol = '₪',
}: SalesInvoiceHistoryProps) {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const totalPages = Math.ceil(total / pageSize);
  const [searchText, setSearchText] = useState(search || '');
  const sortByParam = String(searchParams.get('sortBy') || '').trim();
  const sortDirParam = String(searchParams.get('sortDir') || '').trim();
  const sortBy: SortKey = (
    ['invoiceNumber', 'documentType', 'customerName', 'secondaryCustomerName', 'date', 'grandTotal', 'coverage', 'status', 'linking'].includes(sortByParam)
      ? sortByParam
      : 'date'
  ) as SortKey;
  const sortDir: SortDirection = sortDirParam === 'asc' ? 'asc' : 'desc';

  const handleRowClick = (event: MouseEvent<HTMLTableRowElement>, invoiceId: string) => {
    const target = event.target as HTMLElement | null;
    if (target?.closest('a,button,input,select,textarea,[role="menuitem"]')) {
      return;
    }
    router.push(`/admin/sales/view/${invoiceId}`);
  };

  const buildPageHref = (page: number) => {
    const params = new URLSearchParams(searchParams.toString());
    params.set('page', String(page));
    return `${pathname}?${params.toString()}`;
  };

  const buildDocumentTypeHref = (nextDocumentType?: 'shipment' | 'tax_invoice' | 'all') => {
    const params = new URLSearchParams(searchParams.toString());
    params.set('page', '1');
    if (nextDocumentType) {
      params.set('documentType', nextDocumentType);
    } else {
      params.delete('documentType');
    }
    return `${pathname}?${params.toString()}`;
  };

  const clearSearchQuery = () => {
    const params = new URLSearchParams(searchParams.toString());
    params.delete('search');
    params.set('page', '1');
    setSearchText('');
    const query = params.toString();
    router.push(query ? `${pathname}?${query}` : pathname);
  };

  const buildSortHref = (column: SortKey) => {
    const params = new URLSearchParams(searchParams.toString());
    const nextDir: SortDirection = sortBy === column && sortDir === 'asc' ? 'desc' : 'asc';
    params.set('sortBy', column);
    params.set('sortDir', nextDir);
    params.set('page', '1');
    return `${pathname}?${params.toString()}`;
  };

  const statusBadgeClass = (value: string) => {
    switch (value) {
      case 'cancelled':
        return 'bg-red-100 text-red-800';
      case 'delivered':
        return 'bg-green-100 text-green-800';
      default:
        return 'bg-blue-100 text-blue-800';
    }
  };

  const statusLabel = (value: string) => {
    switch (value) {
      case 'cancelled':
        return 'ملغاة';
      case 'delivered':
        return 'مُسلّمة';
      default:
        return 'نشطة';
    }
  };

  const documentTypeBadgeClass = (value?: SalesInvoice['documentType']) => {
    if (value === 'shipment') return 'bg-amber-100 text-amber-800';
    return 'bg-cyan-100 text-cyan-800';
  };

  const documentTypeLabel = (value?: SalesInvoice['documentType']) => {
    if (value === 'shipment') return 'إرسالية';
    return 'فاتورة ضريبية';
  };

  const normalizeCustomerName = (name?: string) => {
    const normalized = String(name || '').trim();
    if (!normalized) return 'زبون نقدي';
    if (normalized === 'Cash Customer' || normalized === 'cash customer') return 'زبون نقدي';
    if (normalized === 'زبون غير معروف') return 'زبون نقدي';
    return normalized;
  };

  const normalizeSecondaryCustomerName = (name?: string) => {
    const normalized = String(name || '').trim();
    if (!normalized) return '—';
    return normalized;
  };

  const visibleTotals = {
    totalCount: invoices.length,
    shipmentCount: invoices.filter((invoice) => invoice.documentType === 'shipment').length,
    taxInvoiceCount: invoices.filter((invoice) => (invoice.documentType || 'tax_invoice') === 'tax_invoice').length,
    totalAmount: invoices.reduce((sum, invoice) => sum + Number(invoice.grandTotal || 0), 0),
  };

  const sortedInvoices = useMemo(() => {
    const list = [...invoices];
    const direction = sortDir === 'asc' ? 1 : -1;

    list.sort((a, b) => {
      let left: string | number = '';
      let right: string | number = '';

      switch (sortBy) {
        case 'invoiceNumber':
          left = String(a.invoiceNumber || '');
          right = String(b.invoiceNumber || '');
          break;
        case 'documentType':
          left = String(a.documentType || 'tax_invoice');
          right = String(b.documentType || 'tax_invoice');
          break;
        case 'customerName':
          left = normalizeCustomerName(a.customerName);
          right = normalizeCustomerName(b.customerName);
          break;
        case 'secondaryCustomerName':
          left = normalizeSecondaryCustomerName((a as any).secondaryCustomerName);
          right = normalizeSecondaryCustomerName((b as any).secondaryCustomerName);
          break;
        case 'date':
          left = new Date(String(a.date || '')).getTime() || 0;
          right = new Date(String(b.date || '')).getTime() || 0;
          break;
        case 'grandTotal':
          left = Number(a.grandTotal || 0);
          right = Number(b.grandTotal || 0);
          break;
        case 'coverage':
          left = Number(a.secondaryCoveragePercent || 0);
          right = Number(b.secondaryCoveragePercent || 0);
          break;
        case 'status':
          left = String(a.status || '');
          right = String(b.status || '');
          break;
        case 'linking':
          left = (a as any).taxInvoiceId ? 1000 : (Array.isArray((a as any).linkedShipmentIds) ? (a as any).linkedShipmentIds.length : 0);
          right = (b as any).taxInvoiceId ? 1000 : (Array.isArray((b as any).linkedShipmentIds) ? (b as any).linkedShipmentIds.length : 0);
          break;
      }

      if (typeof left === 'number' && typeof right === 'number') {
        return (left - right) * direction;
      }
      return String(left).localeCompare(String(right), 'ar', { numeric: true, sensitivity: 'base' }) * direction;
    });

    return list;
  }, [invoices, sortBy, sortDir]);

  return (
    <Card>
      <CardHeader>
        <CardTitle>قائمة الفواتير</CardTitle>
      </CardHeader>
      <CardContent className="space-y-4">
        {/* Search Bar */}
        <form method="get" className="grid grid-cols-1 md:grid-cols-5 gap-2">
          <div className="relative md:col-span-2">
            <Input
              name="search"
              placeholder="ابحث برقم الفاتورة أو اسم العميل"
              value={searchText}
              onChange={(event) => setSearchText(event.target.value)}
              className="md:col-span-2 pe-9"
            />
            {searchText.trim().length > 0 && (
              <Button
                type="button"
                variant="ghost"
                size="icon"
                onClick={clearSearchQuery}
                className="absolute end-1 top-1/2 h-7 w-7 -translate-y-1/2 text-muted-foreground hover:text-foreground"
                title="مسح البحث"
                aria-label="مسح البحث"
              >
                <X className="h-4 w-4" />
              </Button>
            )}
          </div>
          <select
            name="status"
            defaultValue={status || ''}
            className="h-10 rounded-md border border-input bg-background px-3 py-2 text-sm"
          >
            <option value="">كل الحالات</option>
            <option value="active">نشطة</option>
            <option value="delivered">مُسلّمة</option>
            <option value="cancelled">ملغاة</option>
          </select>
          <select
            name="documentType"
            defaultValue={documentType || ''}
            className="h-10 rounded-md border border-input bg-background px-3 py-2 text-sm"
          >
            <option value="">كل الأنواع</option>
            <option value="tax_invoice">فاتورة ضريبية</option>
            <option value="shipment">إرسالية</option>
          </select>
          <div className="flex gap-2">
            <Button type="submit" className="flex-1">بحث</Button>
            <Button asChild variant="outline" className="flex-1">
              <Link href="/admin/sales/history">إعادة ضبط</Link>
            </Button>
          </div>
        </form>

        <div className="grid grid-cols-2 md:grid-cols-4 gap-2">
          <div className="rounded-md border bg-muted/20 p-3">
            <div className="text-xs text-muted-foreground">عدد النتائج</div>
            <div className="text-lg font-semibold">{visibleTotals.totalCount}</div>
          </div>
          <div className="rounded-md border bg-muted/20 p-3">
            <div className="text-xs text-muted-foreground">فواتير ضريبية</div>
            <div className="text-lg font-semibold">{visibleTotals.taxInvoiceCount}</div>
          </div>
          <div className="rounded-md border bg-muted/20 p-3">
            <div className="text-xs text-muted-foreground">إرساليات</div>
            <div className="text-lg font-semibold">{visibleTotals.shipmentCount}</div>
          </div>
          <div className="rounded-md border bg-muted/20 p-3">
            <div className="text-xs text-muted-foreground">إجمالي القيم</div>
            <div className="text-lg font-semibold">{currencySymbol}{visibleTotals.totalAmount.toFixed(2)}</div>
          </div>
        </div>

        {/* Invoices Table */}
        {invoices.length === 0 ? (
          <div className="text-center py-8 text-muted-foreground">
            لا توجد فواتير مطابقة
          </div>
        ) : (
          <>
            <div className="flex flex-wrap items-center gap-2">
              <span className="text-sm text-muted-foreground">تصفية النوع:</span>
              <Button asChild size="sm" variant={!documentType ? 'secondary' : 'outline'}>
                <Link href={buildDocumentTypeHref(undefined)}>فواتير فقط</Link>
              </Button>
              <Button asChild size="sm" variant={documentType === 'all' ? 'secondary' : 'outline'}>
                <Link href={buildDocumentTypeHref('all')}>الكل (مع إرساليات)</Link>
              </Button>
              <Button asChild size="sm" variant={documentType === 'tax_invoice' ? 'secondary' : 'outline'}>
                <Link href={buildDocumentTypeHref('tax_invoice')}>فاتورة ضريبية</Link>
              </Button>
              <Button asChild size="sm" variant={documentType === 'shipment' ? 'secondary' : 'outline'}>
                <Link href={buildDocumentTypeHref('shipment')}>إرسالية فقط</Link>
              </Button>
            </div>

            <div className="border rounded-md overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>
                      <Button asChild variant="ghost" size="sm" className="h-auto px-0 font-medium">
                        <Link href={buildSortHref('invoiceNumber')}>
                          رقم الفاتورة
                          <ArrowUpDown className="ms-1 h-3.5 w-3.5" />
                        </Link>
                      </Button>
                    </TableHead>
                    <TableHead>
                      <Button asChild variant="ghost" size="sm" className="h-auto px-0 font-medium">
                        <Link href={buildSortHref('documentType')}>
                          نوع المستند
                          <ArrowUpDown className="ms-1 h-3.5 w-3.5" />
                        </Link>
                      </Button>
                    </TableHead>
                    <TableHead>
                      <Button asChild variant="ghost" size="sm" className="h-auto px-0 font-medium">
                        <Link href={buildSortHref('customerName')}>
                          العميل
                          <ArrowUpDown className="ms-1 h-3.5 w-3.5" />
                        </Link>
                      </Button>
                    </TableHead>
                    <TableHead>
                      <Button asChild variant="ghost" size="sm" className="h-auto px-0 font-medium">
                        <Link href={buildSortHref('secondaryCustomerName')}>
                          العميل الفرعي
                          <ArrowUpDown className="ms-1 h-3.5 w-3.5" />
                        </Link>
                      </Button>
                    </TableHead>
                    <TableHead>
                      <Button asChild variant="ghost" size="sm" className="h-auto px-0 font-medium">
                        <Link href={buildSortHref('date')}>
                          التاريخ
                          <ArrowUpDown className="ms-1 h-3.5 w-3.5" />
                        </Link>
                      </Button>
                    </TableHead>
                    <TableHead>
                      <Button asChild variant="ghost" size="sm" className="h-auto px-0 font-medium">
                        <Link href={buildSortHref('grandTotal')}>
                          الإجمالي
                          <ArrowUpDown className="ms-1 h-3.5 w-3.5" />
                        </Link>
                      </Button>
                    </TableHead>
                    <TableHead>
                      <Button asChild variant="ghost" size="sm" className="h-auto px-0 font-medium">
                        <Link href={buildSortHref('coverage')}>
                          الذمم
                          <ArrowUpDown className="ms-1 h-3.5 w-3.5" />
                        </Link>
                      </Button>
                    </TableHead>
                    <TableHead>
                      <Button asChild variant="ghost" size="sm" className="h-auto px-0 font-medium">
                        <Link href={buildSortHref('status')}>
                          الحالة
                          <ArrowUpDown className="ms-1 h-3.5 w-3.5" />
                        </Link>
                      </Button>
                    </TableHead>
                    <TableHead>
                      <Button asChild variant="ghost" size="sm" className="h-auto px-0 font-medium">
                        <Link href={buildSortHref('linking')}>
                          الربط
                          <ArrowUpDown className="ms-1 h-3.5 w-3.5" />
                        </Link>
                      </Button>
                    </TableHead>
                    <TableHead>الإجراءات</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {sortedInvoices.map((invoice) => (
                    <TableRow
                      key={invoice.id}
                      className="cursor-pointer"
                      onClick={(event) => handleRowClick(event, invoice.id)}
                    >
                      <TableCell className="font-medium">
                        <Link
                          href={`/admin/sales/view/${invoice.id}`}
                          className="text-primary underline underline-offset-2 hover:no-underline"
                        >
                          {invoice.invoiceNumber}
                        </Link>
                      </TableCell>
                      <TableCell>
                        <span className={`text-xs px-2 py-1 rounded ${documentTypeBadgeClass(invoice.documentType)}`}>
                          {documentTypeLabel(invoice.documentType)}
                        </span>
                      </TableCell>
                      <TableCell>{normalizeCustomerName(invoice.customerName)}</TableCell>
                      <TableCell>{normalizeSecondaryCustomerName((invoice as any).secondaryCustomerName)}</TableCell>
                      <TableCell>
                        {formatDateStable(invoice.date)}
                      </TableCell>
                      <TableCell>
                        {currencySymbol}{invoice.grandTotal.toFixed(2)}
                      </TableCell>
                      <TableCell className="text-xs">
                        {(() => {
                          const hasSecondary = Boolean(String((invoice as any).secondaryCustomerId || '').trim());
                          const secondaryPercent = Math.max(0, Math.min(100, Number((invoice as any).secondaryCoveragePercent || 0)));
                          if (!hasSecondary || secondaryPercent <= 0) {
                            return <span className="text-muted-foreground">رئيسية 100%</span>;
                          }

                          const grandTotal = Number(invoice.grandTotal || 0);
                          const secondaryAmount = Number((invoice as any).secondaryCoverageAmount || 0) > 0
                            ? Number((invoice as any).secondaryCoverageAmount || 0)
                            : Number(((grandTotal * secondaryPercent) / 100).toFixed(2));
                          const primaryAmount = Number((invoice as any).primaryCoverageAmount || 0) > 0
                            ? Number((invoice as any).primaryCoverageAmount || 0)
                            : Number((grandTotal - secondaryAmount).toFixed(2));
                          const primaryPercent = Number((100 - secondaryPercent).toFixed(2));

                          return (
                            <div className="space-y-1">
                              <div className="rounded bg-muted/40 px-2 py-1">
                                <span className="font-medium">رئيسية:</span>{' '}
                                {primaryPercent.toFixed(2)}% ({currencySymbol}{primaryAmount.toFixed(2)})
                              </div>
                              <div className="rounded bg-muted/40 px-2 py-1">
                                <span className="font-medium">فرعية:</span>{' '}
                                {secondaryPercent.toFixed(2)}% ({currencySymbol}{secondaryAmount.toFixed(2)})
                              </div>
                            </div>
                          );
                        })()}
                      </TableCell>
                      <TableCell>
                        <span className={`text-xs px-2 py-1 rounded ${statusBadgeClass(invoice.status)}`}>
                          {statusLabel(invoice.status)}
                        </span>
                      </TableCell>
                      <TableCell className="text-xs text-muted-foreground">
                        {(invoice as any).taxInvoiceId && (
                          <Link
                            href={`/admin/sales/view/${(invoice as any).taxInvoiceId}`}
                            className="text-primary underline underline-offset-2 hover:no-underline"
                          >
                            فاتورة ضريبية
                          </Link>
                        )}
                        {Array.isArray((invoice as any).linkedShipmentIds) && (invoice as any).linkedShipmentIds.length > 0 && (
                          <span className="text-amber-600">
                            {(invoice as any).linkedShipmentIds.length} إرسالية
                          </span>
                        )}
                        {!(invoice as any).taxInvoiceId && !(Array.isArray((invoice as any).linkedShipmentIds) && (invoice as any).linkedShipmentIds.length > 0) && (
                          <span>—</span>
                        )}
                      </TableCell>
                      <TableCell>
                        <DropdownMenu>
                          <DropdownMenuTrigger asChild>
                            <Button variant="ghost" size="sm">
                              <MoreHorizontal className="h-4 w-4" />
                              <span className="sr-only">إجراءات</span>
                            </Button>
                          </DropdownMenuTrigger>
                          <DropdownMenuContent align="end">
                            <DropdownMenuItem asChild>
                              <Link href={`/admin/sales/view/${invoice.id}`}>عرض</Link>
                            </DropdownMenuItem>
                            {invoice.status === 'cancelled' || invoice.postingStatus === 'posted' || invoice.shippingStatus === 'shipped' || invoice.shippingStatus === 'delivered' ? (
                              <DropdownMenuItem disabled title="لا يمكن تعديل فاتورة مرحلة أو ملغاة">تعديل</DropdownMenuItem>
                            ) : (
                              <DropdownMenuItem asChild>
                                <Link href={`/admin/sales/edit/${invoice.id}`}>تعديل</Link>
                              </DropdownMenuItem>
                            )}
                            {invoice.status !== 'cancelled' && invoice.documentType !== 'shipment' && (
                              <DropdownMenuItem asChild>
                                <Link href={`/admin/sales/returns?invoiceId=${invoice.id}`}>إنشاء مردود مبيعات</Link>
                              </DropdownMenuItem>
                            )}
                          </DropdownMenuContent>
                        </DropdownMenu>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>

            {/* Pagination */}
            <div className="flex flex-col gap-2 md:flex-row md:items-center md:justify-between">
              <div className="text-sm text-muted-foreground">
                الصفحة {currentPage} من {Math.max(totalPages, 1)} (الإجمالي: {total} فاتورة)
              </div>
              <div className="flex gap-2">
                <Button
                  asChild
                  variant="outline"
                  size="sm"
                  disabled={currentPage <= 1}
                >
                  <Link href={buildPageHref(Math.max(1, currentPage - 1))}>السابق</Link>
                </Button>
                <Button
                  asChild
                  variant="outline"
                  size="sm"
                  disabled={currentPage >= totalPages}
                >
                  <Link href={buildPageHref(Math.min(totalPages || 1, currentPage + 1))}>التالي</Link>
                </Button>
              </div>
            </div>
          </>
        )}
      </CardContent>
    </Card>
  );
}
