import type { BannerListItem } from "@/features/objects/lib/data";
import { API_URLS } from "@/shared/config/api/URLs";
import { Button } from "@/shared/ui/button";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/shared/ui/table";
import { Check, Loader2, Trash2 } from "lucide-react";
import { useEffect, useState, type Dispatch, type SetStateAction } from "react";

interface Props {
  filteredData: BannerListItem[] | [];
  setEditingPlan: Dispatch<SetStateAction<BannerListItem | null>>;
  setDialogOpen: Dispatch<SetStateAction<boolean>>;
  handleDelete: (object: BannerListItem) => void;
  isLoading: boolean;
  isError: boolean;
  handleOrderChange: ({ body, id }: { id: number; body: FormData }) => void; // tartib raqamini update qilish uchun
}

const ObjectTable = ({
  filteredData,
  handleDelete,
  isError,
  isLoading,
  handleOrderChange,
}: Props) => {
  // Mahsulotlar tartibini local state orqali boshqaramiz
  const [localOrders, setLocalOrders] = useState<{ [key: number]: number }>({});

  useEffect(() => {
    const orders = filteredData.reduce(
      (acc, item) => {
        acc[item.id] = item.order;
        return acc;
      },
      {} as { [key: number]: number },
    );
    setLocalOrders(orders);
  }, [filteredData]);

  const onOrderChange = (id: number, value: string) => {
    if (value === "") {
      // bo'sh inputni ham qabul qilamiz
      setLocalOrders((prev) => ({ ...prev, [id]: 0 })); // yoki null ham bo'lishi mumkin
      return;
    }

    const num = parseInt(value, 10);
    if (!isNaN(num)) {
      setLocalOrders((prev) => ({ ...prev, [id]: num }));
    }
  };

  return (
    <div className="flex-1 overflow-auto">
      {isLoading && (
        <div className="h-full flex items-center justify-center bg-white/70 z-10">
          <span className="text-lg font-medium">
            <Loader2 className="animate-spin" />
          </span>
        </div>
      )}

      {isError && (
        <div className="h-full flex items-center justify-center z-10">
          <span className="text-lg font-medium text-red-600">
            Ma'lumotlarni olishda xatolik yuz berdi.
          </span>
        </div>
      )}

      {!isError && !isLoading && (
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>#</TableHead>
              <TableHead>Banner</TableHead>
              <TableHead>Tartib raqami</TableHead>
              <TableHead className="text-right">Amallar</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {filteredData && filteredData.length > 0 ? (
              filteredData.map((item, index) => (
                <TableRow key={item.id}>
                  <TableCell>{index + 1}</TableCell>
                  <TableCell className="font-medium">
                    <img
                      src={API_URLS.BASE_URL + item.banner}
                      alt={item.id.toString()}
                      className="w-16 h-16"
                    />
                  </TableCell>
                  <TableCell className="font-medium flex items-center gap-2">
                    <input
                      type="number"
                      value={localOrders[item.id] ?? ""}
                      onChange={(e) => onOrderChange(item.id, e.target.value)}
                      onKeyDown={(e) => {
                        if (e.key === "Enter") {
                          const formData = new FormData();
                          formData.append(
                            "order",
                            localOrders[item.id].toString(),
                          );
                          handleOrderChange({
                            id: item.id,
                            body: formData,
                          });
                        }
                      }}
                      className="w-24 h-10 border rounded px-2"
                    />
                    <Button
                      size="icon"
                      variant="outline"
                      onClick={() => {
                        const formData = new FormData();
                        formData.append(
                          "order",
                          localOrders[item.id].toString(),
                        );
                        handleOrderChange({
                          id: item.id,
                          body: formData,
                        });
                      }}
                    >
                      <Check size={18} />
                    </Button>
                  </TableCell>
                  <TableCell className="text-right space-x-2 gap-2">
                    <Button
                      variant="destructive"
                      size="icon"
                      className="cursor-pointer"
                      onClick={() => handleDelete(item)}
                    >
                      <Trash2 size={18} />
                    </Button>
                  </TableCell>
                </TableRow>
              ))
            ) : (
              <TableRow>
                <TableCell colSpan={5} className="text-center py-4 text-lg">
                  Obyekt topilmadi.
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      )}
    </div>
  );
};

export default ObjectTable;
