"use client";

import React, { useState, useMemo, useEffect } from "react";
import Image from "next/image";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import {
  Edit,
  AlertTriangle,
  ArrowLeft,
  CircleDashed,
  ChevronLeft,
  ChevronRight,
} from "lucide-react";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import Link from "next/link";
import {
  useGetInventorysQuery,
  useUpdateInventorysMutation,
} from "@/redux/services/inventory.api";
import { useGetCategoriesQuery } from "@/redux/services/categories.api";
import { toast } from "@/components/ui/use-toast";
import { useRouter } from "next/navigation";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";

type Inventory = {
  inventoryId: string;
  productName: string;
  categoryName: string;
  quantity: number;
};

type Category = {
  _id: string;
  name: string;
  icon: string;
};

export default function InventoryManagement() {
  // params: {
  // params: { slug: string };
  // }
  const branchName = "JP";
  const {
    data: products,
    isLoading: isProductsLoading,
    isSuccess: isProductsSuccess,
    refetch,
    error: productsError,
  } = useGetInventorysQuery(branchName);

  useEffect(() => {
    if (isProductsSuccess) {
      refetch();
    }
  }, [isProductsSuccess, refetch]);

  const [updateInventory, { isLoading: updateLoading, error: updateerror }] =
    useUpdateInventorysMutation({});

  const {
    data: categories,
    isLoading: isCategoryLoading,
    error: categoryError,
  } = useGetCategoriesQuery();

  const [selectedProduct, setSelectedProduct] = useState<Inventory | null>(
    null
  );
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const [editedProduct, setEditedProduct] = useState<Inventory | null>(null);
  const [showUpdateAlert, setShowUpdateAlert] = useState(false);
  const [selectedCategory, setSelectedCategory] = useState<string>("all");
  const [addQuantity, setAddQuantity] = useState<number>(0);
  const [searchTerm, setSearchTerm] = useState<string>("");

  // Pagination state
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);
  const [goToPage, setGoToPage] = useState("");

  useEffect(() => {
    setCurrentPage(1);
  }, [selectedCategory, searchTerm]);

  const handleEditProduct = (product: Inventory) => {
    setSelectedProduct(product);
    setEditedProduct({ ...product });
    setIsEditDialogOpen(true);
  };

  const handleUpdateProduct = () => {
    updateInventory({
      inventoryId: selectedProduct!.inventoryId,
      quantity: addQuantity,
    })
      .unwrap()
      .then((res) => {
        setIsEditDialogOpen(false);
        setEditedProduct(null);
        if (res.status) {
          return toast({
            title: res.message,
            variant: "success",
          });
        }
        return toast({
          title: res.message,
          variant: "destructive",
        });
      })
      .catch((err: any) => console.log("err", err));
  };

  const filteredProducts = useMemo(() => {
    return products?.filter((product) => {
      const matchesCategory =
        selectedCategory === "all" || product.categoryName === selectedCategory;
      const matchesSearch =
        product.productName &&
        product.productName.toLowerCase().includes(searchTerm.toLowerCase());
      return matchesCategory && matchesSearch;
    });
  }, [products, selectedCategory, searchTerm]);

  // Pagination logic
  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentItems = filteredProducts?.slice(
    indexOfFirstItem,
    indexOfLastItem
  );
  const totalPages = Math.ceil((filteredProducts?.length || 0) / itemsPerPage);

  const handlePageChange = (pageNumber: number) => {
    setCurrentPage(pageNumber);
  };

  const handleGoToPage = () => {
    const pageNumber = parseInt(goToPage);
    if (pageNumber > 0 && pageNumber <= totalPages) {
      setCurrentPage(pageNumber);
      setGoToPage("");
    }
  };

  return (
    <div className="container mx-auto p-4">
      <h1 className="text-3xl font-bold mb-6">
        {/* <div className="flex items-center justify-between mb-6">
          <Link
            href="/inventory-management"
            className="flex items-center text-primary"
          >
            <ArrowLeft className="mr-2 hover:animate-pulse hover:-translate-x-2 transition" />
            <span className="capitalize">
              {branchName
                .replace(/-/g, " ")
                .replace(/(^\w{1})|(\s\w{1})/g, (match) =>
                  match.toUpperCase()
                )}{" "}
            </span>
          </Link>
        </div> */}
      </h1>

      {showUpdateAlert && (
        <Alert className="mb-4">
          <AlertTriangle className="h-4 w-4" />
          <AlertTitle>Success</AlertTitle>
          <AlertDescription>
            The product has been successfully updated.
          </AlertDescription>
        </Alert>
      )}

      <div className="mb-6 flex gap-4">
        <div>
          <Label htmlFor="category-filter" className="mb-2 block">
            Filter by Category
          </Label>
          <Select
            value={selectedCategory}
            onValueChange={(value) => setSelectedCategory(value)}
          >
            <SelectTrigger id="category-filter" className="w-[200px]">
              <SelectValue placeholder="All Categories" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All Categories</SelectItem>
              {categories &&
                categories.length > 0 &&
                categories?.map((category) => (
                  <SelectItem key={category._id} value={category.name}>
                    <div className="flex items-center space-x-2">
                      <Avatar>
                        {category.icon && category.icon.length > 0 ? (
                          <Image
                            src={category.icon}
                            height={200}
                            width={200}
                            alt="BI"
                          />
                        ) : (
                          <AvatarFallback>
                            {category.name.charAt(0)}
                          </AvatarFallback>
                        )}
                      </Avatar>
                      {/* <Avatar>
                      <AvatarImage src={category.icon} alt={category.name} />
                      <AvatarFallback>{category.name.charAt(0)}</AvatarFallback>
                    </Avatar> */}
                      <span>{category.name}</span>
                    </div>
                  </SelectItem>
                ))}
            </SelectContent>
          </Select>
        </div>
        <div className="flex-1">
          <Label htmlFor="search" className="mb-2 block">
            Search Products
          </Label>
          <Input
            id="search"
            type="text"
            placeholder="Search by product name..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="w-full"
          />
        </div>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Inventory</CardTitle>
          <CardDescription>
            View and manage your product inventory
          </CardDescription>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Product Name</TableHead>
                <TableHead>Category</TableHead>
                <TableHead>Quantity</TableHead>
                <TableHead>Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {currentItems?.map((product) => (
                <TableRow key={product.inventoryId}>
                  <TableCell>{product.productName}</TableCell>
                  <TableCell>{product.categoryName}</TableCell>
                  <TableCell>{product.quantity}</TableCell>
                  <TableCell>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => handleEditProduct(product)}
                    >
                      <Edit className="mr-2 h-4 w-4" />
                      Edit
                    </Button>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
          {isProductsLoading && (
            <div>
              <div className="flex justify-center items-center h-[50vh]">
                <CircleDashed className="animate-spin text-[#be063f]" />
              </div>
            </div>
          )}
          <div className="flex justify-between items-center mt-4">
            <div>
              Showing {indexOfFirstItem + 1} to{" "}
              {Math.min(indexOfLastItem, filteredProducts?.length || 0)} of{" "}
              {filteredProducts?.length || 0} items
            </div>
            <div className="flex items-center gap-2">
              <Button
                variant="outline"
                size="sm"
                onClick={() => handlePageChange(currentPage - 1)}
                disabled={currentPage === 1}
              >
                <ChevronLeft className="h-4 w-4 mr-2" />
                Previous
              </Button>
              <span className="mx-2">
                Page {currentPage} of {totalPages}
              </span>
              <Button
                variant="outline"
                size="sm"
                onClick={() => handlePageChange(currentPage + 1)}
                disabled={currentPage === totalPages}
              >
                Next
                <ChevronRight className="h-4 w-4 ml-2" />
              </Button>
              <div className="flex items-center ml-4">
                <Input
                  type="number"
                  placeholder="Go to page"
                  value={goToPage}
                  onChange={(e) => setGoToPage(e.target.value)}
                  className="w-20 mr-2"
                />
                <Button variant="outline" size="sm" onClick={handleGoToPage}>
                  Go
                </Button>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      <Dialog open={isEditDialogOpen} onOpenChange={setIsEditDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Edit Product</DialogTitle>
            <DialogDescription>
              Update the product details below.
            </DialogDescription>
          </DialogHeader>
          {editedProduct && (
            <div className="grid gap-4 py-4">
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="name" className="text-right">
                  Name
                </Label>
                <Input
                  id="name"
                  value={editedProduct.productName}
                  readOnly
                  className="col-span-3 cursor-not-allowed"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="category" className="text-right">
                  Category
                </Label>
                <Input
                  id="category"
                  value={editedProduct.categoryName}
                  readOnly
                  className="col-span-3 cursor-not-allowed"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="quantity" className="text-right">
                  Current Quantity
                </Label>
                <Input
                  id="quantity"
                  type="number"
                  value={editedProduct.quantity}
                  readOnly
                  className="col-span-3 cursor-not-allowed"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="add-quantity" className="text-right">
                  Add Quantity
                </Label>
                <Input
                  id="add-quantity"
                  type="number"
                  value={addQuantity}
                  onChange={(e) => setAddQuantity(parseInt(e.target.value))}
                  className="col-span-3"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="total-quantity" className="text-right">
                  Total Quantity
                </Label>
                <Input
                  id="total-quantity"
                  type="number"
                  value={editedProduct.quantity + addQuantity}
                  readOnly
                  className="col-span-3"
                />
              </div>
            </div>
          )}
          <DialogFooter>
            <Button variant="appVariant" onClick={handleUpdateProduct}>
              Save Changes
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
