import Link from 'next/link';
import { redirect } from 'next/navigation';
import { getSession } from '@/lib/auth';
import { handleListSalesInvoices } from '@/lib/actions/sales-invoice.actions';
import { formatDateDDMMYYYY } from '@/lib/utils';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';

export const metadata = { title: 'Shipped Invoices | Sales' };

export default async function ShippedPage() {
  const session = await getSession();
  if (!session?.user) {
    redirect('/login');
  }

  const result = await handleListSalesInvoices({ take: 500 });
  const invoices = result.success ? result.data?.items || [] : [];

  const shipped = invoices.filter(
    (invoice) =>
      invoice.shippingStatus === 'shipped' ||
      invoice.shippingStatus === 'partial' ||
      invoice.shippingStatus === 'delivered'
  );

  const shippedCount = shipped.filter((row) => row.shippingStatus === 'shipped').length;
  const deliveredCount = shipped.filter((row) => row.shippingStatus === 'delivered').length;
  const partialCount = shipped.filter((row) => row.shippingStatus === 'partial').length;

  return (
    <div className="space-y-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">{shippedCount}</p>
            </div>
            <div className="rounded-md border p-4">
              <p className="text-sm text-muted-foreground">تسليم جزئي</p>
              <p className="text-2xl font-bold">{partialCount}</p>
            </div>
            <div className="rounded-md border p-4">
              <p className="text-sm text-muted-foreground">تم التسليم</p>
              <p className="text-2xl font-bold">{deliveredCount}</p>
            </div>
          </div>

          <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>
                {shipped.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={6} className="text-center text-muted-foreground py-8">
                      لا توجد فواتير مشحونة بعد.
                    </TableCell>
                  </TableRow>
                ) : (
                  shipped.map((invoice) => (
                    <TableRow key={invoice.id}>
                      <TableCell className="font-medium">{invoice.invoiceNumber}</TableCell>
                      <TableCell>{invoice.customerName}</TableCell>
                      <TableCell>
                        {invoice.shipmentDate
                          ? formatDateDDMMYYYY(invoice.shipmentDate)
                          : '-'}
                      </TableCell>
                      <TableCell>{invoice.shipmentId || '-'}</TableCell>
                      <TableCell>{invoice.shippingStatus}</TableCell>
                      <TableCell>
                        <Button asChild variant="outline" size="sm">
                          <Link href={`/admin/sales/view/${invoice.id}`}>عرض</Link>
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
