"use client";

import React, { useState, useMemo, useEffect, Suspense } 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,
  CircleDashed,
  ChevronLeft,
  ChevronRight,
} from "lucide-react";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  useGetUrgentRequestsQuery,
  useUpdateInventorysMutation,
} from "@/redux/services/inventory.api";
import { useGetBranchQuery } from "@/redux/services/branchs.api";
import { useGetCategoriesQuery } from "@/redux/services/categories.api";
import { toast } from "@/components/ui/use-toast";
import { Avatar } from "@radix-ui/react-avatar";
import { AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { useSearchParams } from "next/navigation";

type UrgentReq = {
  _id: string;
  branchName?: string;
  inventoryId: string;
  productName: string;
  categoryName: string;
  quantity: number;
};

const LoadingState = () => (
  <div className="flex items-center justify-center p-8">
    <CircleDashed className="h-8 w-8 animate-spin" />
  </div>
);

export default function UrgentRequestsManagement() {
  return (
    <Suspense fallback={<LoadingState />}>
      <UrgentRequestsContent />
    </Suspense>
  );
}

function UrgentRequestsContent() {
  const searchParams = useSearchParams();
  const branchName = searchParams.get("branchName") || "all";
  const productName = searchParams.get("productName") || "";

  const {
    data: products,
    isLoading: isProductsLoading,
    isSuccess: isProductsSuccess,
    refetch,
    error: productsError,
  } = useGetUrgentRequestsQuery();

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

  const {
    data: branches,
    isLoading: isBranchesLoading,
    error: branchesError,
  } = useGetBranchQuery();

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

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

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

  const [currentPage, setCurrentPage] = useState(1);
  const [goToPage, setGoToPage] = useState<string>("");
  const itemsPerPage = 10;

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

  const handleUpdateProduct = () => {
    updateInventory({
      inventoryId: selectedProduct!._id,
      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 matchesBranch =
        selectedBranch === "all" || product.branchName === selectedBranch;
      const matchesSearch =
        product.productName &&
        product.productName.toLowerCase().includes(searchTerm.toLowerCase());
      return matchesCategory && matchesBranch && matchesSearch;
    });
  }, [
    products,
    selectedCategory,
    selectedBranch,
    searchTerm,
    branchName,
    productName,
  ]);

  const totalPages = Math.ceil((filteredProducts?.length || 0) / itemsPerPage);
  const paginatedProducts = filteredProducts?.slice(
    (currentPage - 1) * itemsPerPage,
    currentPage * itemsPerPage
  );

  const handleGoToPage = () => {
    const pageNumber = parseInt(goToPage, 10);
    if (pageNumber >= 1 && pageNumber <= totalPages) {
      setCurrentPage(pageNumber);
      setGoToPage("");
    } else {
      toast({
        title: "Invalid page number",
        description: `Please enter a number between 1 and ${totalPages}`,
        variant: "destructive",
      });
    }
  };

  useEffect(() => {
    setCurrentPage(1);
  }, [selectedCategory, searchTerm, selectedBranch]);
  useEffect(() => {
    setSelectedBranch(branchName);
    setSearchTerm(productName);
  }, [branchName, productName]);
  return (
    <div className="container mx-auto p-4">
      {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?.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).toUpperCase()}
                        </AvatarFallback>
                      )}
                    </Avatar>
                    {/* <Avatar>
                      <AvatarImage src={category.icon} alt={category.name} />
                      <AvatarFallback className="h-10 w-10 rounded-full">
                        {category.name.charAt(0).toUpperCase()}
                      </AvatarFallback>
                    </Avatar> */}
                    <span>{category.name}</span>
                  </div>
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
        <div>
          <Label htmlFor="branch-filter" className="mb-2 block">
            Filter by Branch
          </Label>
          <Select
            value={selectedBranch}
            onValueChange={(value) => setSelectedBranch(value)}
          >
            <SelectTrigger id="branch-filter" className="w-[200px]">
              <SelectValue placeholder="All Branches" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All Branches</SelectItem>
              {branches?.map((branch) => (
                <SelectItem key={branch._id} value={branch.name}>
                  {branch.name}
                </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>Branch Name</TableHead>
                <TableHead>Category</TableHead>
                <TableHead>Quantity</TableHead>
                <TableHead>Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {paginatedProducts?.map((product) => (
                <TableRow key={product._id}>
                  <TableCell>{product.productName}</TableCell>
                  <TableCell>{product.branchName}</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>
        </CardContent>
      </Card>

      <div className="mt-4 flex items-center justify-between">
        <div className="flex items-center gap-2">
          <Button
            variant="ghost"
            onClick={() => setCurrentPage((prev) => Math.max(prev - 1, 1))}
            disabled={currentPage === 1}
          >
            <ChevronLeft className="h-4 w-4" />
          </Button>
          <span>
            Page {currentPage} of {totalPages}
          </span>
          <Button
            variant="ghost"
            onClick={() =>
              setCurrentPage((prev) => Math.min(prev + 1, totalPages))
            }
            disabled={currentPage === totalPages}
          >
            <ChevronRight className="h-4 w-4" />
          </Button>
        </div>
        <div className="flex items-center gap-2">
          <Input
            type="number"
            placeholder="Go to page..."
            value={goToPage}
            onChange={(e) => setGoToPage(e.target.value)}
            className="w-[100px]"
          />
          <Button onClick={handleGoToPage}>Go</Button>
        </div>
      </div>
    </div>
  );
}
