import React, { useState, useEffect } from "react";
import { apiFetch } from '@/utils/api';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "../ui/table";
import { Skeleton } from "../ui/skeleton";

// Define the structure of purchase order items
interface PurchaseOrderItem {
  id: string | number;
  pid: string | number;
  product_name: string;
  sku: string;
  upc: string;
  ordered: number;
  received: number;
  po_cost_price: number;
  cost_each?: number; // For receiving items
  qty_each?: number; // For receiving items
  total_cost: number;
  receiving_status?: string;
}

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 PurchaseOrderAccordionProps {
  purchaseOrder: PurchaseOrder;
  children: React.ReactNode;
  rowClassName?: string;
}

export default function PurchaseOrderAccordion({
  purchaseOrder,
  children,
  rowClassName,
}: PurchaseOrderAccordionProps) {
  const [isOpen, setIsOpen] = useState(false);
  const [items, setItems] = useState<PurchaseOrderItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  
  // Clone the TableRow (children) and add the onClick handler and className
  const enhancedRow = React.cloneElement(children as React.ReactElement, {
    onClick: () => setIsOpen(!isOpen),
    className: `${(children as React.ReactElement).props.className || ""} cursor-pointer ${isOpen ? 'bg-gray-100' : ''} ${rowClassName || ""}`.trim(),
    "data-state": isOpen ? "open" : "closed"
  });

  // Format currency
  const formatCurrency = (value: number) => {
    return `$${value.toLocaleString("en-US", {
      minimumFractionDigits: 2,
      maximumFractionDigits: 2,
    })}`;
  };

  useEffect(() => {
    // Only fetch items when the accordion is open
    if (!isOpen) return;

    const fetchItems = async () => {
      setLoading(true);
      setError(null);
      
      try {
        // Endpoint path will depend on the type of record
        const endpoint = purchaseOrder.record_type === "receiving_only" 
          ? `/api/purchase-orders/receiving/${purchaseOrder.id}/items`
          : `/api/purchase-orders/${purchaseOrder.id}/items`;
          
        const response = await apiFetch(endpoint);
        
        if (!response.ok) {
          throw new Error(`Failed to fetch items: ${response.statusText}`);
        }
        
        const data = await response.json();
        setItems(data);
      } catch (err) {
        console.error("Error fetching purchase order items:", err);
        setError(err instanceof Error ? err.message : "Unknown error occurred");
      } finally {
        setLoading(false);
      }
    };

    fetchItems();
  }, [purchaseOrder.id, purchaseOrder.record_type, isOpen]);
  
  // Render purchase order items list
  const renderItemsList = () => {
    if (error) {
      return (
        <div className="p-4 text-red-500">
          Error loading items: {error}
        </div>
      );
    }

    return (
      <div className="max-h-[600px] overflow-y-auto bg-gray-50 rounded-md p-2">
        <Table className="w-full">
          <TableHeader className="bg-white sticky top-0 z-10">
            <TableRow>
              <TableHead className="w-[100px]">Item Number</TableHead>
              <TableHead className="w-auto">Product</TableHead>
              <TableHead className="w-[100px]">UPC</TableHead>
              <TableHead className="w-[80px] text-right">Ordered</TableHead>
              <TableHead className="w-[80px] text-right">Received</TableHead>
              <TableHead className="w-[100px] text-right">Unit Cost</TableHead>
              <TableHead className="w-[100px] text-right">Total Cost</TableHead>
              {purchaseOrder.record_type !== "po_only" && (
                <TableHead className="w-[120px] text-right">Status</TableHead>
              )}
            </TableRow>
          </TableHeader>
          <TableBody>
            {loading ? (
              // Loading skeleton
              Array(5).fill(0).map((_, i) => (
                <TableRow key={`skeleton-${i}`}>
                  <TableCell><Skeleton className="h-5 w-full" /></TableCell>
                  <TableCell><Skeleton className="h-5 w-full" /></TableCell>
                  <TableCell><Skeleton className="h-5 w-full" /></TableCell>
                  <TableCell><Skeleton className="h-5 w-full" /></TableCell>
                  <TableCell><Skeleton className="h-5 w-full" /></TableCell>
                  <TableCell><Skeleton className="h-5 w-full" /></TableCell>
                  <TableCell><Skeleton className="h-5 w-full" /></TableCell>
                  {purchaseOrder.record_type !== "po_only" && (
                    <TableCell><Skeleton className="h-5 w-full" /></TableCell>
                  )}
                </TableRow>
              ))
            ) : (
              items.map((item) => (
                <TableRow key={item.id} className="hover:bg-gray-100">
                  <TableCell className="">
                    <a 
                      href={`https://backend.acherryontop.com/product/${item.pid}`}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="hover:underline"
                      onClick={(e) => e.stopPropagation()}
                    >
                      {item.sku}
                    </a>
                  </TableCell>
                  <TableCell className="font-medium">
                    <a 
                      href={`https://backend.acherryontop.com/product/${item.pid}`}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="hover:underline"
                      onClick={(e) => e.stopPropagation()}
                    >
                      {item.product_name}
                    </a>
                  </TableCell>
                  <TableCell className="">
                    <a 
                      href={`https://backend.acherryontop.com/product/${item.pid}`}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="hover:underline"
                      onClick={(e) => e.stopPropagation()}
                    >
                      {item.upc}
                    </a>
                  </TableCell>
                  <TableCell className="text-right">
                    {item.ordered}
                  </TableCell>
                  <TableCell className="text-right">
                    {item.received || 0}
                  </TableCell>
                  <TableCell className="text-right">
                    {formatCurrency(item.po_cost_price || item.cost_each || 0)}
                  </TableCell>
                  <TableCell className="text-right">
                    {formatCurrency(item.total_cost)}
                  </TableCell>
                  {purchaseOrder.record_type !== "po_only" && (
                    <TableCell className="text-right">
                      {item.receiving_status || "Unknown"}
                    </TableCell>
                  )}
                </TableRow>
              ))
            )}
            
            {!loading && items.length === 0 && (
              <TableRow>
                <TableCell colSpan={purchaseOrder.record_type === "po_only" ? 7 : 8} className="text-center py-4 text-muted-foreground">
                  No items found for this order
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </div>
    );
  };
  
  return (
    <>
      {/* First render the row which will serve as the trigger */}
      {enhancedRow}
      
      {/* Then render the accordion content conditionally if open */}
      {isOpen && (
        <TableRow className="p-0 border-0">
          <TableCell colSpan={12} className="p-0 border-0">
            <div className="pt-2 pb-4 px-4 bg-gray-50 border-t border-b">
              <div className="mb-2 text-sm text-muted-foreground">
                {purchaseOrder.total_items} product{purchaseOrder.total_items !== 1 ? "s" : ""} in this {purchaseOrder.record_type === "receiving_only" ? "receiving" : "purchase order"}
              </div>
              {renderItemsList()}
            </div>
          </TableCell>
        </TableRow>
      )}
    </>
  );
} 
