"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import Layout from "@/components/layout/layout";
import { Button } from "@/components/ui/button";
import { Table, TableHeader, TableRow, TableHead, TableBody, TableCell } from "@/components/ui/table";
import { Input } from "@/components/ui/input";
import { Product } from "@/models/products";
import { Package, RefreshCw } from "lucide-react";
import { fetchProductData, updateProductStock } from "@/lib/productData";
import { toast } from "sonner";

export default function StockManagementPage() {
  const router = useRouter();
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [editingStock, setEditingStock] = useState<Record<string, boolean>>({});
  const [stockValues, setStockValues] = useState<Record<string, number>>({});
  const [searchTerm, setSearchTerm] = useState<string>("");

  useEffect(() => {
    const authToken = document.cookie
      .split("; ")
      .find((row) => row.startsWith("Authorization="))
      ?.split("=")[1];

    if (!authToken) {
      router.push("/login");
      return;
    }

    const fetchDataAsync = async () => {
      try {
        const fetchedProducts = await fetchProductData("/api/products", authToken);
        setProducts(fetchedProducts);
        
        // Initialize stock values
        const initialStockValues: Record<string, number> = {};
        fetchedProducts.forEach((product: Product) => {
          if (product._id) {
            initialStockValues[product._id] = product.currentStock || 0;
          }
        });
        setStockValues(initialStockValues);
        
        setLoading(false);
      } catch (error) {
        console.error("Error fetching products:", error);
        setLoading(false);
      }
    };

    fetchDataAsync();
  }, [router]);

  const handleEditStock = (productId: string) => {
    setEditingStock({
      ...editingStock,
      [productId]: true,
    });
  };

  const handleSaveStock = async (product: Product) => {
    if (!product._id) return;
    
    const authToken = document.cookie
      .split("; ")
      .find((row) => row.startsWith("Authorization="))
      ?.split("=")[1];

    if (!authToken) {
      router.push("/login");
      return;
    }

    try {
      const newStockValue = stockValues[product._id] || 0;
      
      await updateProductStock(
        product._id,
        {
          currentStock: newStockValue,
          stockTracking: product.stockTracking
        },
        authToken
      );

      // Update local products state
      setProducts(products.map(p => {
        if (p._id === product._id) {
          return {
            ...p,
            currentStock: newStockValue
          };
        }
        return p;
      }));

      setEditingStock({
        ...editingStock,
        [product._id]: false,
      });

      toast.success("Stock updated successfully");
    } catch (error) {
      console.error("Error updating stock:", error);
      toast.error("Failed to update stock");
    }
  };

  const handleStockChange = (productId: string, value: number) => {
    setStockValues({
      ...stockValues,
      [productId]: value,
    });
  };

  const getStockStatus = (product: Product) => {
    if (!product.stockTracking) return "Not Tracked";
    
    if (!product.currentStock || product.currentStock <= 0) {
      return "Out of Stock";
    } else if (product.lowStockThreshold && product.currentStock <= product.lowStockThreshold) {
      return "Low Stock";
    } else {
      return "In Stock";
    }
  };

  const filteredProducts = products.filter(product => {
    const matchesSearch = 
      !searchTerm || 
      product.name.toLowerCase().includes(searchTerm.toLowerCase());
    
    return matchesSearch;
  });

  const statsData = {
    total: products.length,
    inStock: products.filter(p => p.stockTracking && p.currentStock && p.currentStock > 0 && (!p.lowStockThreshold || p.currentStock > p.lowStockThreshold)).length,
    lowStock: products.filter(p => p.stockTracking && p.lowStockThreshold && p.currentStock && p.currentStock <= p.lowStockThreshold && p.currentStock > 0).length,
    outOfStock: products.filter(p => p.stockTracking && (!p.currentStock || p.currentStock <= 0)).length,
    notTracked: products.filter(p => p.stockTracking === false).length
  };

  return (
    <Layout>
      <div className="container mx-auto">
        <div className="flex justify-between items-center mb-8">
          <h1 className="text-2xl font-bold">Stock Management</h1>
          <Button onClick={() => router.push("/dashboard/products")}>
            <Package className="mr-2 h-4 w-4" />
            Manage Products
          </Button>
        </div>

        <div className="grid grid-cols-5 gap-4 mb-8">
          <div className="bg-background rounded-lg border border-border p-4">
            <div className="text-3xl font-bold">{statsData.total}</div>
            <div className="text-sm text-muted-foreground">Total Products</div>
          </div>
          
          <div className="bg-background rounded-lg border border-border p-4">
            <div className="text-3xl font-bold text-green-500">{statsData.inStock}</div>
            <div className="text-sm text-muted-foreground">In Stock</div>
          </div>
          
          <div className="bg-background rounded-lg border border-border p-4">
            <div className="text-3xl font-bold text-amber-500">{statsData.lowStock}</div>
            <div className="text-sm text-muted-foreground">Low Stock</div>
          </div>
          
          <div className="bg-background rounded-lg border border-border p-4">
            <div className="text-3xl font-bold text-red-500">{statsData.outOfStock}</div>
            <div className="text-sm text-muted-foreground">Out of Stock</div>
          </div>
          
          <div className="bg-background rounded-lg border border-border p-4">
            <div className="text-3xl font-bold text-gray-500">{statsData.notTracked}</div>
            <div className="text-sm text-muted-foreground">Not Tracked</div>
          </div>
        </div>

        <div className="bg-background rounded-lg border border-border">
          <div className="p-4 border-b border-border flex justify-between items-center">
            <h2 className="text-xl font-semibold">Inventory List</h2>
            <div className="flex items-center gap-2">
              <Input
                placeholder="Search products..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="w-64"
              />
              <Button 
                variant="outline" 
                size="icon"
                onClick={() => setSearchTerm("")}
              >
                <RefreshCw className="h-4 w-4" />
              </Button>
            </div>
          </div>
          
          <div className="overflow-x-auto">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Product</TableHead>
                  <TableHead>Unit</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead>Current Stock</TableHead>
                  <TableHead>Low Stock Threshold</TableHead>
                  <TableHead className="text-right">Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {loading ? (
                  <TableRow>
                    <TableCell colSpan={6} className="h-24 text-center">
                      Loading...
                    </TableCell>
                  </TableRow>
                ) : filteredProducts.length > 0 ? (
                  filteredProducts.map((product) => (
                    <TableRow key={product._id}>
                      <TableCell className="font-medium">{product.name}</TableCell>
                      <TableCell>{product.unitType}</TableCell>
                      <TableCell className={
                        product.stockTracking === false ? "text-gray-500" :
                        !product.currentStock || product.currentStock <= 0 ? "text-red-500" :
                        product.lowStockThreshold && product.currentStock <= product.lowStockThreshold ? "text-amber-500" :
                        "text-green-500"
                      }>
                        {getStockStatus(product)}
                      </TableCell>
                      <TableCell>
                        {editingStock[product._id as string] ? (
                          <Input
                            type="number"
                            min="0"
                            step={product.unitType === "gr" ? "0.1" : "1"}
                            value={stockValues[product._id as string]}
                            onChange={(e) => handleStockChange(product._id as string, parseFloat(e.target.value))}
                            className="max-w-[100px]"
                          />
                        ) : (
                          product.stockTracking ? 
                            `${product.currentStock || 0} ${product.unitType}` : 
                            "N/A"
                        )}
                      </TableCell>
                      <TableCell>
                        {product.stockTracking ? 
                          `${product.lowStockThreshold || 0} ${product.unitType}` : 
                          "N/A"}
                      </TableCell>
                      <TableCell className="text-right">
                        {product.stockTracking && (
                          editingStock[product._id as string] ? (
                            <Button 
                              size="sm" 
                              onClick={() => handleSaveStock(product)}
                            >
                              Save
                            </Button>
                          ) : (
                            <Button 
                              variant="outline" 
                              size="sm" 
                              onClick={() => handleEditStock(product._id as string)}
                            >
                              Update Stock
                            </Button>
                          )
                        )}
                      </TableCell>
                    </TableRow>
                  ))
                ) : (
                  <TableRow>
                    <TableCell colSpan={6} className="h-24 text-center">
                      No products found.
                    </TableCell>
                  </TableRow>
                )}
              </TableBody>
            </Table>
          </div>
        </div>
      </div>
    </Layout>
  );
} 