import Link from 'next/link';
import type { SalesReturn } from '@/lib/modules/sales';
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';

type SalesReturnsListProps = {
  salesReturns: SalesReturn[];
};

function statusLabel(status: string): string {
  switch (status) {
    case 'pending':
      return 'قيد المراجعة';
    case 'approved':
      return 'معتمد';
    case 'received':
      return 'مستلم';
    case 'processed':
      return 'مُعالج';
    case 'rejected':
      return 'مرفوض';
    case 'cancelled':
      return 'ملغي';
    default:
      return status;
  }
}

export default function SalesReturnsList({ salesReturns }: SalesReturnsListProps) {
  return (
    <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>
                <TableHead>القيد المحاسبي</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {salesReturns.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={7} className="text-center text-muted-foreground py-8">
                    لا توجد مردودات مبيعات مسجلة بعد.
                  </TableCell>
                </TableRow>
              ) : (
                salesReturns
                  .slice()
                  .sort(
                    (a, b) =>
                      new Date(String(b.createdAt || b.date || 0)).getTime()
                      - new Date(String(a.createdAt || a.date || 0)).getTime()
                  )
                  .map((salesReturn) => {
                    const returnId = String(salesReturn.id || '').trim();
                    const creditJeId = `JE-SR-CN-${returnId}`;
                    const refundJeId = `JE-SR-RF-${returnId}`;
                    const canShowLinks = String(salesReturn.status || '').trim() === 'processed' && Boolean(returnId);

                    return (
                      <TableRow key={salesReturn.id}>
                        <TableCell className="font-medium">{salesReturn.returnNumber}</TableCell>
                        <TableCell>{salesReturn.invoiceNumber}</TableCell>
                        <TableCell>{salesReturn.customerName}</TableCell>
                        <TableCell>{formatDateStable(salesReturn.date)}</TableCell>
                        <TableCell>{Number(salesReturn.totalAmount || 0).toFixed(2)}</TableCell>
                        <TableCell>{statusLabel(String(salesReturn.status || ''))}</TableCell>
                        <TableCell>
                          {!canShowLinks ? (
                            <span className="text-xs text-muted-foreground">غير متاح بعد</span>
                          ) : (
                            <div className="flex flex-col gap-1 text-xs">
                              <Link
                                href={`/admin/accounting/entries?je=${encodeURIComponent(creditJeId)}&q=${encodeURIComponent(String(salesReturn.returnNumber || returnId))}`}
                                className="text-primary underline underline-offset-2 hover:no-underline"
                              >
                                قيد إشعار الدائن
                              </Link>
                              <Link
                                href={`/admin/accounting/entries?je=${encodeURIComponent(refundJeId)}&q=${encodeURIComponent(String(salesReturn.returnNumber || returnId))}`}
                                className="text-primary underline underline-offset-2 hover:no-underline"
                              >
                                قيد الاسترداد
                              </Link>
                            </div>
                          )}
                        </TableCell>
                      </TableRow>
                    );
                  })
              )}
            </TableBody>
          </Table>
        </div>
      </CardContent>
    </Card>
  );
}
