"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 { Switch } from "@/components/ui/switch";
import { 
  DropdownMenu, 
  DropdownMenuContent, 
  DropdownMenuItem, 
  DropdownMenuTrigger 
} from "@/components/ui/dropdown-menu";
import { 
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Product } from "@/models/products";
import { Package, RefreshCw, ChevronDown, CheckSquare, XSquare } from "lucide-react";
import { fetchProductData, updateProductStock, saveProductData } 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>("");
  const [selectedProducts, setSelectedProducts] = useState<string[]>([]);
  const [isConfirmDialogOpen, setIsConfirmDialogOpen] = useState(false);
  const [bulkAction, setBulkAction] = useState<'enable' | 'disable' | null>(null);

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

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

    const fetchDataAsync = async () => {
      try {
        const apiUrl = `${process.env.NEXT_PUBLIC_API_URL}/products`;
        const fetchedProducts = await fetchProductData(apiUrl, 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 handleToggleStockTracking = 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 apiUrl = `${process.env.NEXT_PUBLIC_API_URL}/products/${product._id}`;
      
      // Toggle the stock tracking status
      const newTrackingStatus = !product.stockTracking;
      
      // For enabling tracking, we need to ensure there's a stock value
      const stockData = {
        stockTracking: newTrackingStatus,
        currentStock: product.currentStock || 0,
        lowStockThreshold: product.lowStockThreshold || 10,
      };
      
      // Update product with new tracking status
      await saveProductData(
        apiUrl,
        stockData,
        authToken,
        "PUT"
      );
      
      // Also update stock API to ensure consistency
      await updateProductStock(
        product._id,
        stockData,
        authToken
      );

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

      toast.success(`Stock tracking ${newTrackingStatus ? 'enabled' : 'disabled'} for ${product.name}`);
    } catch (error) {
      console.error("Error toggling stock tracking:", error);
      toast.error(`Failed to ${product.stockTracking ? 'disable' : 'enable'} stock tracking`);
    }
  };

  const handleBulkAction = async (action: 'enable' | 'disable') => {
    if (selectedProducts.length === 0) {
      toast.error("No products selected");
      return;
    }

    setBulkAction(action);
    setIsConfirmDialogOpen(true);
  };

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

    if (!authToken || !bulkAction) {
      setIsConfirmDialogOpen(false);
      return;
    }

    setLoading(true);

    try {
      const isEnabling = bulkAction === 'enable';
      const updatePromises = selectedProducts.map(async (productId) => {
        const product = products.find(p => p._id === productId);
        if (!product) return null;

        const apiUrl = `${process.env.NEXT_PUBLIC_API_URL}/products/${productId}`;
        
        const stockData = {
          stockTracking: isEnabling,
          currentStock: product.currentStock || 0,
          lowStockThreshold: product.lowStockThreshold || 10,
        };
        
        // Update product with new tracking status
        await saveProductData(
          apiUrl,
          stockData,
          authToken,
          "PUT"
        );
        
        // Also update stock API to ensure consistency
        await updateProductStock(
          productId,
          stockData,
          authToken
        );

        return productId;
      });

      await Promise.all(updatePromises);

      // Update local state
      setProducts(products.map(p => {
        if (selectedProducts.includes(p._id as string)) {
          return {
            ...p,
            stockTracking: isEnabling,
          };
        }
        return p;
      }));

      setSelectedProducts([]);
      toast.success(`Stock tracking ${isEnabling ? 'enabled' : 'disabled'} for ${selectedProducts.length} products`);
    } catch (error) {
      console.error(`Error ${bulkAction}ing stock tracking:`, error);
      toast.error(`Failed to ${bulkAction} stock tracking`);
    } finally {
      setLoading(false);
      setIsConfirmDialogOpen(false);
    }
  };

  const toggleSelectProduct = (productId: string) => {
    setSelectedProducts(prev => 
      prev.includes(productId) 
        ? prev.filter(id => id !== productId) 
        : [...prev, productId]
    );
  };

  const toggleSelectAll = () => {
    if (selectedProducts.length === filteredProducts.length) {
      setSelectedProducts([]);
    } else {
      setSelectedProducts(filteredProducts.map(p => p._id as string));
    }
  };

  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>
          <div className="flex space-x-3">
            <Button onClick={() => router.push("/dashboard/products")}>
              <Package className="mr-2 h-4 w-4" />
              Manage Products
            </Button>
          </div>
        </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">
            <div className="flex items-center gap-3">
              <h2 className="text-xl font-semibold">Inventory List</h2>
              {selectedProducts.length > 0 && (
                <DropdownMenu>
                  <DropdownMenuTrigger asChild>
                    <Button variant="outline" size="sm" className="ml-2">
                      Bulk Actions <ChevronDown className="ml-2 h-4 w-4" />
                    </Button>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent>
                    <DropdownMenuItem onClick={() => handleBulkAction('enable')}>
                      <CheckSquare className="mr-2 h-4 w-4" />
                      Enable Tracking
                    </DropdownMenuItem>
                    <DropdownMenuItem onClick={() => handleBulkAction('disable')}>
                      <XSquare className="mr-2 h-4 w-4" />
                      Disable Tracking
                    </DropdownMenuItem>
                  </DropdownMenuContent>
                </DropdownMenu>
              )}
            </div>
            <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 className="w-[30px]">
                    <input 
                      type="checkbox" 
                      className="h-4 w-4 rounded border-gray-300"
                      checked={selectedProducts.length > 0 && selectedProducts.length === filteredProducts.length}
                      onChange={toggleSelectAll}
                    />
                  </TableHead>
                  <TableHead>Product</TableHead>
                  <TableHead>Unit</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead>Current Stock</TableHead>
                  <TableHead>Low Stock Threshold</TableHead>
                  <TableHead>Track Stock</TableHead>
                  <TableHead className="text-right">Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {loading ? (
                  <TableRow>
                    <TableCell colSpan={8} className="h-24 text-center">
                      Loading...
                    </TableCell>
                  </TableRow>
                ) : filteredProducts.length > 0 ? (
                  filteredProducts.map((product) => (
                    <TableRow key={product._id}>
                      <TableCell>
                        <input 
                          type="checkbox"
                          className="h-4 w-4 rounded border-gray-300"
                          checked={selectedProducts.includes(product._id as string)}
                          onChange={() => toggleSelectProduct(product._id as string)}
                        />
                      </TableCell>
                      <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>
                        <Switch
                          checked={product.stockTracking === true}
                          onCheckedChange={() => handleToggleStockTracking(product)}
                        />
                      </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={8} className="h-24 text-center">
                      No products found.
                    </TableCell>
                  </TableRow>
                )}
              </TableBody>
            </Table>
          </div>
        </div>

        <AlertDialog open={isConfirmDialogOpen} onOpenChange={setIsConfirmDialogOpen}>
          <AlertDialogContent>
            <AlertDialogHeader>
              <AlertDialogTitle>
                {bulkAction === 'enable' ? 'Enable' : 'Disable'} Stock Tracking
              </AlertDialogTitle>
              <AlertDialogDescription>
                Are you sure you want to {bulkAction === 'enable' ? 'enable' : 'disable'} stock tracking for {selectedProducts.length} selected products?
                {bulkAction === 'disable' && ' This will remove any stock tracking for these products.'}
                {bulkAction === 'enable' && ' This will enable stock tracking with initial values.'}
              </AlertDialogDescription>
            </AlertDialogHeader>
            <AlertDialogFooter>
              <AlertDialogCancel>Cancel</AlertDialogCancel>
              <AlertDialogAction onClick={executeBulkAction}>
                Confirm
              </AlertDialogAction>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>
      </div>
    </Layout>
  );
} 