import React, { memo, useCallback, useMemo, useState } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "../../../../../src/components/ui/dialog";

import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "../../../../../src/components/ui/table";

import { ArrowDown, ArrowUp, X } from "lucide-react";

type StockItem = {
  _id: string;
  sku: string;
  quantity: number;
  price: {
    $numberDecimal: string;
  };
  comparePrice: {
    $numberDecimal: string;
  };
  product: {
    _id: string;
    name: string;
    slug: string;
  };
  color: {
    _id: string;
    name: string;
    hexCode: string;
  };
  size: {
    _id: string;
    name: string;
  };
  createdAt: string;
  updatedAt: string;
};

type SortField = "color" | "size" | "sku" | "quantity";

type Props = {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  data: StockItem[];
};

const ViewStocks: React.FC<Props> = ({
  open,
  onOpenChange,
  data,
}) => {
    console.log('Skus', data)
  const [sort, setSort] = useState<{
    field: SortField;
    order: "asc" | "desc";
  }>({
    field: "sku",
    order: "asc",
  });

  const handleSort = useCallback((field: SortField) => {
    setSort((prev) => ({
      field,
      order:
        prev.field === field
          ? prev.order === "asc"
            ? "desc"
            : "asc"
          : "asc",
    }));
  }, []);

  const sortedStocks = useMemo(() => {
    const cloned = [...data];

    cloned.sort((a, b) => {
      let aValue: string | number = "";
      let bValue: string | number = "";

      switch (sort.field) {
        case "color":
          aValue = a.color.name.toLowerCase();
          bValue = b.color.name.toLowerCase();
          break;

        case "size":
          aValue = a.size.name.toLowerCase();
          bValue = b.size.name.toLowerCase();
          break;

        case "sku":
          aValue = a.sku.toLowerCase();
          bValue = b.sku.toLowerCase();
          break;

        case "quantity":
          aValue = a.quantity;
          bValue = b.quantity;
          break;

        default:
          break;
      }

      if (aValue < bValue) {
        return sort.order === "asc" ? -1 : 1;
      }

      if (aValue > bValue) {
        return sort.order === "asc" ? 1 : -1;
      }

      return 0;
    });

    return cloned;
  }, [data, sort]);

  const productName = useMemo(() => {
    return data?.[0]?.product?.name || "Stocks";
  }, [data]);

  const renderSortIcon = useCallback(
    (field: SortField) => {
      if (sort.field !== field) {
        return (
          <ArrowDown className="h-3 w-3 text-muted-foreground/40" />
        );
      }

      return sort.order === "asc" ? (
        <ArrowUp className="h-3 w-3" />
      ) : (
        <ArrowDown className="h-3 w-3" />
      );
    },
    [sort]
  );

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-3xl">
          <div className="flex items-center max-w-lg min-h-[calc(100%-0.5rem)] my-2 mx-auto">
            <div className="relative flex flex-col w-full rounded-lg gap-0 border-0 border-stroke bg-white p-0 shadow-lg text-dark-5 dark:border-dark-3 dark:bg-[#1f2a37] dark:text-white">
                {/* Header */}
                <DialogHeader className="p-4 bg-primary flex flex-row items-center justify-between">
                    <div>
                    <p className="text-xs text-white uppercase tracking-wide mb-1">
                        Product Stocks
                    </p>

                    <DialogTitle className="text-white text-base font-medium">
                        {productName} — Stock Manager
                    </DialogTitle>
                    </div>

                    <X
                    className="h-6 w-6 p-1 text-white cursor-pointer"
                    onClick={() => onOpenChange(false)}
                    />
                </DialogHeader>

                {/* Body */}
                <div className="p-4">
                    <div className="border rounded-md overflow-hidden">
                    {/* Top Bar */}
                    <div className="px-6 py-4 border-b bg-primary dark:bg-[#1f2a37] flex items-center justify-between">
                        <p className="text-xs font-medium text-white uppercase tracking-wide">
                        Existing Stocks
                        </p>

                        <span className="text-xs border rounded-full px-2.5 py-0.5 text-white">
                        {data.length} Item{data.length !== 1 ? "s" : ""}
                        </span>
                    </div>

                    {/* Table */}
                    <Table>
                        <TableHeader className="dark:bg-[#1f2a37]">
                        <TableRow>
                            {[
                            {
                                key: "color",
                                label: "Color",
                                className: "pl-6",
                            },
                            {
                                key: "size",
                                label: "Size",
                            },
                            {
                                key: "sku",
                                label: "SKU Code",
                            },
                            {
                                key: "quantity",
                                label: "Qty",
                            },
                            ].map((item) => (
                            <TableHead
                                key={item.key}
                                className={`text-xs cursor-pointer hover:bg-muted/40 select-none ${
                                item.className || ""
                                }`}
                                onClick={() =>
                                handleSort(item.key as SortField)
                                }
                            >
                                <div className="flex items-center gap-1">
                                {item.label}
                                {renderSortIcon(item.key as SortField)}
                                </div>
                            </TableHead>
                            ))}
                        </TableRow>
                        </TableHeader>

                        <TableBody className="dark:bg-[#1f2a37]">
                        {sortedStocks.length === 0 ? (
                            <TableRow>
                            <TableCell
                                colSpan={4}
                                className="text-center text-muted-foreground py-10 text-sm"
                            >
                                No stocks available
                            </TableCell>
                            </TableRow>
                        ) : (
                            sortedStocks.map((stock) => (
                            <TableRow key={stock._id}>
                                {/* Color */}
                                <TableCell className="pl-6">
                                <div className="flex items-center gap-2">
                                    <span
                                    className="w-2.5 h-2.5 rounded-full border flex-shrink-0"
                                    style={{
                                        backgroundColor:
                                        stock.color.hexCode,
                                    }}
                                    />

                                    <span className="text-sm capitalize">
                                    {stock.color.name}
                                    </span>
                                </div>
                                </TableCell>

                                {/* Size */}
                                <TableCell className="text-sm">
                                {stock.size.name}
                                </TableCell>

                                {/* SKU */}
                                <TableCell className="font-mono text-xs text-muted-foreground">
                                {stock.sku}
                                </TableCell>

                                {/* Quantity */}
                                <TableCell className="text-sm">
                                {stock.quantity}
                                </TableCell>
                            </TableRow>
                            ))
                        )}
                        </TableBody>
                    </Table>
                    </div>
                </div>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
};

export default memo(ViewStocks);