import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "../ui/table";
import { Badge } from "../ui/badge";
import { Button } from "../ui/button";
import { Skeleton } from "../ui/skeleton";
import { FileText } from "lucide-react";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "../ui/tooltip";
import {
  getPurchaseOrderStatusLabel,
  getReceivingStatusLabel,
  getPurchaseOrderStatusVariant,
  getReceivingStatusVariant,
} from "../../types/status-codes";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "../ui/card";
import PurchaseOrderAccordion from "./PurchaseOrderAccordion";

interface PurchaseOrder {
  id: number | string;
  vendor_name: string;
  order_date: string | null;
  receiving_date: string | null;
  status: number;
  total_items: number;
  total_quantity: number;
  total_cost: number;
  total_received: number;
  fulfillment_rate: number;
  short_note: string | null;
  record_type: "po_only" | "po_with_receiving" | "receiving_only";
}

interface PurchaseOrdersTableProps {
  purchaseOrders: PurchaseOrder[];
  loading: boolean;
  summary: { order_count: number } | null;
  sortColumn: string;
  sortDirection: "asc" | "desc";
  handleSort: (column: string) => void;
}

export default function PurchaseOrdersTable({ 
  purchaseOrders, 
  loading, 
  summary,
  sortColumn,
  sortDirection,
  handleSort
}: PurchaseOrdersTableProps) {
  // Helper functions
  const getRecordTypeIndicator = (recordType: string) => {
    switch (recordType) {
      case "po_with_receiving":
        return (
          <Badge
            variant="outline"
            className="flex items-center justify-center border-green-500 text-green-700 bg-green-50 px-0 text-xs w-[85px]"
          >
            Received PO
          </Badge>
        );
      case "po_only":
        return (
          <Badge
            variant="outline"
            className="flex items-center justify-center border-blue-500 text-blue-700 bg-blue-50 px-0 text-xs w-[85px]"
          >
            PO
          </Badge>
        );
      case "receiving_only":
        return (
          <Badge
            variant="outline"
            className="flex items-center justify-center border-amber-500 text-amber-700 bg-amber-50 px-0 text-xs w-[85px]"
          >
            Receiving
          </Badge>
        );
      default:
        return (
          <Badge
            variant="outline"
            className="flex items-center justify-center border-gray-500 text-gray-700 bg-gray-50 px-0 text-xs w-[85px]"
          >
            {recordType || "Unknown"}
          </Badge>
        );
    }
  };

  const getStatusBadge = (status: number, recordType: string) => {
    if (recordType === "receiving_only") {
      return (
        <Badge
          className="w-[115px] flex items-center text-xs justify-center px-1"
          variant={getReceivingStatusVariant(status)}
        >
          {getReceivingStatusLabel(status)}
        </Badge>
      );
    }

    return (
      <Badge
        className="w-[115px] flex items-center text-xs justify-center px-1"
        variant={getPurchaseOrderStatusVariant(status)}
      >
        {getPurchaseOrderStatusLabel(status)}
      </Badge>
    );
  };

  const formatNumber = (value: number) => {
    return value.toLocaleString("en-US", {
      minimumFractionDigits: 2,
      maximumFractionDigits: 2,
    });
  };

  const formatCurrency = (value: number) => {
    return `$${formatNumber(value)}`;
  };

  const formatPercent = (value: number) => {
    return (
      (value * 100).toLocaleString("en-US", {
        minimumFractionDigits: 1,
        maximumFractionDigits: 1,
      }) + "%"
    );
  };

  // Update sort indicators in table headers
  const getSortIndicator = (column: string) => {
    if (sortColumn !== column) return null;
    return sortDirection === "asc" ? " ↑" : " ↓";
  };
  
  return (
    <Card className="mb-6">
      <CardHeader className="flex flex-row items-center justify-between">
        <CardTitle>Purchase Orders & Receivings</CardTitle>
        <div className="text-sm text-muted-foreground">
          {loading ? (
            <Skeleton className="h-4 w-24" />
          ) : (
            `${summary?.order_count.toLocaleString()} orders`
          )}
        </div>
      </CardHeader>
      <CardContent>
        <Table
          className="table-fixed"
          style={{ tableLayout: "fixed", width: "100%"}}
        >
          <TableHeader>
            <TableRow>
              <TableHead className="w-[100px] text-center">Type</TableHead>
              <TableHead className="w-[60px] text-center">
                <Button
                  className="w-full"
                  variant="ghost"
                  onClick={() => !loading && handleSort("id")}
                  disabled={loading}
                >
                  ID{getSortIndicator("id")}
                </Button>
              </TableHead>
              <TableHead className="w-[140px] text-center">
                <Button
                  className="w-full"
                  variant="ghost"
                  onClick={() => !loading && handleSort("vendor_name")}
                  disabled={loading}
                >
                  Supplier{getSortIndicator("vendor_name")}
                </Button>
              </TableHead>
              <TableHead className="w-[115px] text-center">
                <Button
                  className="w-full"
                  variant="ghost"
                  onClick={() => !loading && handleSort("status")}
                  disabled={loading}
                >
                  Status{getSortIndicator("status")}
                </Button>
              </TableHead>
              <TableHead className="w-[150px] text-center">Note</TableHead>
              <TableHead className="w-[90px] text-center">
                <Button
                  className="w-full"
                  variant="ghost"
                  onClick={() => !loading && handleSort("total_cost")}
                  disabled={loading}
                >
                  Total Cost{getSortIndicator("total_cost")}
                </Button>
              </TableHead>
              <TableHead className="w-[70px] text-center">
                <Button
                  className="w-full"
                  variant="ghost"
                  onClick={() => !loading && handleSort("total_items")}
                  disabled={loading}
                >
                  Products{getSortIndicator("total_items")}
                </Button>
              </TableHead>
              <TableHead className="w-[90px] text-center">
                <Button
                  className="w-full"
                  variant="ghost"
                  onClick={() => !loading && handleSort("order_date")}
                  disabled={loading}
                >
                  Order Date{getSortIndicator("order_date")}
                </Button>
              </TableHead>
              <TableHead className="w-[90px] text-center">
                <Button
                  className="w-full"
                  variant="ghost"
                  onClick={() => !loading && handleSort("receiving_date")}
                  disabled={loading}
                >
                  Rec'd Date{getSortIndicator("receiving_date")}
                </Button>
              </TableHead>
              <TableHead className="w-[70px] text-center">
                <Button
                  className="w-full"
                  variant="ghost"
                  onClick={() => !loading && handleSort("total_quantity")}
                  disabled={loading}
                >
                  Ordered{getSortIndicator("total_quantity")}
                </Button>
              </TableHead>
              <TableHead className="w-[80px] text-center">
                <Button
                  className="w-full"
                  variant="ghost"
                  onClick={() => !loading && handleSort("total_received")}
                  disabled={loading}
                >
                  Received{getSortIndicator("total_received")}
                </Button>
              </TableHead>
              <TableHead className="w-[80px] text-center">
                <Button
                  className="w-full"
                  variant="ghost"
                  onClick={() => !loading && handleSort("fulfillment_rate")}
                  disabled={loading}
                >
                  % Fulfilled{getSortIndicator("fulfillment_rate")}
                </Button>
              </TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {loading ? (
              // Skeleton rows for loading state
              Array(50)
                .fill(0)
                .map((_, index) => (
                  <TableRow key={`skeleton-${index}`}>
                    <TableCell className="w-[100px]">
                      <Skeleton className="h-6 w-full" />
                    </TableCell>
                    <TableCell className="w-[60px]">
                      <Skeleton className="h-5 w-full" />
                    </TableCell>
                    <TableCell className="w-[140px]">
                      <Skeleton className="h-5 w-full" />
                    </TableCell>
                    <TableCell className="w-[115px]">
                      <Skeleton className="h-6 w-full" />
                    </TableCell>
                    <TableCell className="w-[150px]">
                      <Skeleton className="h-5 w-full" />
                    </TableCell>
                    <TableCell className="w-[90px]">
                      <Skeleton className="h-5 w-full" />
                    </TableCell>
                    <TableCell className="w-[70px]">
                      <Skeleton className="h-5 w-full" />
                    </TableCell>
                    <TableCell className="w-[90px]">
                      <Skeleton className="h-5 w-full" />
                    </TableCell>
                    <TableCell className="w-[90px]">
                      <Skeleton className="h-5 w-full" />
                    </TableCell>
                    <TableCell className="w-[70px]">
                      <Skeleton className="h-5 w-full" />
                    </TableCell>
                    <TableCell className="w-[80px]">
                      <Skeleton className="h-5 w-full" />
                    </TableCell>
                    <TableCell className="w-[80px]">
                      <Skeleton className="h-5 w-full" />
                    </TableCell>
                  </TableRow>
                ))
            ) : purchaseOrders.length > 0 ? (
              purchaseOrders.map((po) => {
                // Determine row styling based on record type
                let rowClassName = "border-l-4 border-l-gray-300"; // Default

                if (po.record_type === "po_with_receiving") {
                  rowClassName = "border-l-4 border-l-green-500";
                } else if (po.record_type === "po_only") {
                  rowClassName = "border-l-4 border-l-blue-500";
                } else if (po.record_type === "receiving_only") {
                  rowClassName = "border-l-4 border-l-amber-500";
                }
                return (
                  <PurchaseOrderAccordion
                    key={`${po.id}-${po.record_type}`}
                    purchaseOrder={po}
                    rowClassName={rowClassName}
                  >
                    <TableRow>
                      <TableCell className="text-center">
                        {getRecordTypeIndicator(po.record_type)}
                      </TableCell>
                      <TableCell className="font-semibold text-center">
                        <a 
                          href={po.record_type === "po_only" 
                            ? `https://backend.acherryontop.com/po/edit/${po.id}` 
                            : `https://backend.acherryontop.com/receiving/edit/${po.id}`}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="hover:underline"
                        >
                          {po.id}
                        </a>
                      </TableCell>
                      <TableCell>{po.vendor_name}</TableCell>
                      <TableCell>
                        {getStatusBadge(po.status, po.record_type)}
                      </TableCell>
                      <TableCell className="truncate text-center">
                        {po.short_note ? (
                          <TooltipProvider>
                            <Tooltip>
                              <TooltipTrigger className="text-left flex items-center gap-1">
                                <FileText className="h-3 w-3" />
                                <span className="truncate">
                                  {po.short_note}
                                </span>
                              </TooltipTrigger>
                              <TooltipContent>
                                <p>{po.short_note}</p>
                              </TooltipContent>
                            </Tooltip>
                          </TooltipProvider>
                        ) : (
                          ""
                        )}
                      </TableCell>
                      <TableCell>{formatCurrency(po.total_cost)}</TableCell>
                      <TableCell className="text-center">{po.total_items.toLocaleString()}</TableCell>
                      <TableCell className="text-center">
                        {po.order_date
                          ? new Date(po.order_date).toLocaleDateString(
                              "en-US",
                              {
                                month: "numeric",
                                day: "numeric",
                                year: "numeric",
                              }
                            )
                          : "-"}
                      </TableCell>
                      <TableCell className="text-center">
                        {po.receiving_date
                          ? new Date(po.receiving_date).toLocaleDateString(
                              "en-US",
                              {
                                month: "numeric",
                                day: "numeric",
                                year: "numeric",
                              }
                            )
                          : "-"}
                      </TableCell>
                      <TableCell className="text-center">
                        {po.record_type === "receiving_only" ? "-" : po.total_quantity.toLocaleString()}
                      </TableCell>
                      <TableCell className="text-center">
                        {po.record_type === "po_only" ? "-" : po.total_received.toLocaleString()}
                      </TableCell>
                      <TableCell className="text-center" >
                        {po.record_type === "po_with_receiving" 
                          ? (po.fulfillment_rate === null ? "N/A" : formatPercent(po.fulfillment_rate))
                          : "-"}
                      </TableCell>
                    </TableRow>
                  </PurchaseOrderAccordion>
                );
              })
            ) : (
              <TableRow>
                <TableCell
                  colSpan={12}
                  className="text-center text-muted-foreground"
                >
                  No purchase orders found
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </CardContent>
    </Card>
  );
} 