
'use client';

import React, { useState, useEffect, useMemo } from 'react';
import { MoreHorizontal, Search, File, Upload, Trash2, Printer } from "lucide-react";

import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Input } from '@/components/ui/input';
import { PageHeader } from "@/components/page-header";
import { getMockInventory, type InventoryItem } from "@/lib/data";
import { InventoryDialog } from '@/components/inventory/inventory-dialog';
import { InventoryFormValues } from '@/components/inventory/inventory-form';
import { AdjustStockDialog } from '@/components/inventory/adjust-stock-dialog';
import { exportToCsv } from '@/lib/utils';
import { ImportDialog } from '@/components/inventory/import-dialog';
import { BarcodeDialog } from '@/components/inventory/barcode-dialog';
import { BulkBarcodeDialog } from '@/components/inventory/bulk-barcode-dialog';

export default function InventoryPage() {
  const [inventory, setInventory] = useState<InventoryItem[]>([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [isImportDialogOpen, setIsImportDialogOpen] = useState(false);
  const [isBulkBarcodeDialogOpen, setIsBulkBarcodeDialogOpen] = useState(false);
  const [editingItem, setEditingItem] = useState<InventoryItem | null>(null);
  const [deletingItem, setDeletingItem] = useState<InventoryItem | null>(null);
  const [adjustingItem, setAdjustingItem] = useState<InventoryItem | null>(null);
  const [printingItem, setPrintingItem] = useState<InventoryItem | null>(null);
  const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());

  const loadData = () => {
    setInventory(getMockInventory());
  };
  
  useEffect(() => {
    loadData();
    window.addEventListener('storage', loadData);
    return () => window.removeEventListener('storage', loadData);
  }, []);

  const updateInventory = (newInventory: InventoryItem[]) => {
      localStorage.setItem('mockInventory', JSON.stringify(newInventory));
      loadData();
      setSelectedItems(new Set()); // Clear selection after update
  };

  const handleFormSubmit = (data: InventoryFormValues) => {
    if (editingItem) {
        const updatedInventory = inventory.map(item => 
            item.id === editingItem.id ? { ...editingItem, ...data } : item
        );
        updateInventory(updatedInventory);
    } else {
        const newItem: InventoryItem = {
            id: `FAB${Date.now()}`,
            ...data,
        };
        updateInventory([newItem, ...inventory]);
    }
    closeDialogs();
  };
  
  const handleAdjustStock = (itemId: string, newQuantity: number) => {
    const updatedInventory = inventory.map(item =>
      item.id === itemId ? { ...item, quantity: newQuantity } : item
    );
    updateInventory(updatedInventory);
    setAdjustingItem(null);
  };


  const handleDelete = (item: InventoryItem) => {
    const newInventory = inventory.filter(i => i.id !== item.id);
    updateInventory(newInventory);
    setDeletingItem(null);
  };
  
  const handleBulkDelete = () => {
      const newInventory = inventory.filter(item => !selectedItems.has(item.id));
      updateInventory(newInventory);
      setDeletingItem(null); // Use the same dialog for confirmation
  };

  const openAddDialog = () => {
    setEditingItem(null);
    setIsDialogOpen(true);
  };

  const openEditDialog = (item: InventoryItem) => {
    setEditingItem(item);
    setIsDialogOpen(true);
  };
  
  const openAdjustStockDialog = (item: InventoryItem) => {
    setAdjustingItem(item);
  };

  const openDeleteDialog = (item: InventoryItem) => {
    setDeletingItem(item);
  };
  
  const openBulkDeleteDialog = () => {
    // A bit of a hack: use the deletingItem state to trigger the dialog for bulk delete
    setDeletingItem({ id: 'bulk-delete', name: `${selectedItems.size} items` } as any);
  }
  
  const openBulkBarcodeDialog = () => {
      setIsBulkBarcodeDialogOpen(true);
  }

  const openPrintBarcodeDialog = (item: InventoryItem) => {
    setPrintingItem(item);
  }

  const closeDialogs = () => {
    setIsDialogOpen(false);
    setEditingItem(null);
  };

  const handleExport = () => {
    exportToCsv(filteredInventory, 'inventory.csv');
  };
  
  const handleImport = (newItems: InventoryItem[]) => {
    const updatedInventory = [...inventory];
    newItems.forEach(newItem => {
        const existingIndex = updatedInventory.findIndex(i => i.id === newItem.id);
        if (existingIndex > -1) {
            // Update existing item
            updatedInventory[existingIndex] = newItem;
        } else {
            // Add new item
            updatedInventory.push(newItem);
        }
    });
    updateInventory(updatedInventory);
    setIsImportDialogOpen(false);
  };

  const getStockStatus = (item: InventoryItem) => {
    if (item.quantity === 0) {
      return { text: "Out of Stock", variant: "destructive" as const };
    }
    if (item.quantity < item.lowStockThreshold) {
      return { text: "Low Stock", variant: "secondary" as const };
    }
    return { text: "In Stock", variant: "success" as const };
  };
  
  const handleSelectAll = (checked: boolean) => {
    if (checked) {
      setSelectedItems(new Set(filteredInventory.map(item => item.id)));
    } else {
      setSelectedItems(new Set());
    }
  };

  const handleSelectItem = (itemId: string, checked: boolean) => {
    const newSelection = new Set(selectedItems);
    if (checked) {
      newSelection.add(itemId);
    } else {
      newSelection.delete(itemId);
    }
    setSelectedItems(newSelection);
  };

  const filteredInventory = useMemo(() => inventory.filter(item =>
    item.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
    item.type.toLowerCase().includes(searchTerm.toLowerCase()) ||
    item.color.toLowerCase().includes(searchTerm.toLowerCase()) ||
    item.id.toLowerCase().includes(searchTerm.toLowerCase())
  ), [inventory, searchTerm]);

  const selectedInventoryItems = useMemo(() => 
    inventory.filter(item => selectedItems.has(item.id)),
    [inventory, selectedItems]
  );

  return (
    <div className="flex flex-col gap-4">
      <PageHeader title="Fabric Inventory" actionButtonText="Add Material" onActionButtonClick={openAddDialog}>
        <div className="relative w-full max-w-sm">
          <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
          <Input
            type="search"
            placeholder="Search materials..."
            className="pl-8 w-full"
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
          />
        </div>
        {selectedItems.size > 0 && (
            <>
                <Button size="sm" variant="outline" className="h-8 gap-1" onClick={openBulkBarcodeDialog}>
                    <Printer className="h-3.5 w-3.5" />
                    <span>Print Barcodes ({selectedItems.size})</span>
                </Button>
                <Button size="sm" variant="destructive" className="h-8 gap-1" onClick={openBulkDeleteDialog}>
                    <Trash2 className="h-3.5 w-3.5" />
                    <span>Delete ({selectedItems.size})</span>
                </Button>
            </>
        )}
        <Button size="sm" variant="outline" className="h-8 gap-1" onClick={() => setIsImportDialogOpen(true)}>
            <Upload className="h-3.5 w-3.5" />
            <span className="sr-only sm:not-sr-only sm:whitespace-nowrap">
              Import
            </span>
          </Button>
         <Button size="sm" variant="outline" className="h-8 gap-1" onClick={handleExport}>
            <File className="h-3.5 w-3.5" />
            <span className="sr-only sm:not-sr-only sm:whitespace-nowrap">
              Export
            </span>
          </Button>
      </PageHeader>

      <InventoryDialog
        isOpen={isDialogOpen}
        onOpenChange={setIsDialogOpen}
        item={editingItem}
        onSubmit={handleFormSubmit}
      />
      
      <ImportDialog 
        isOpen={isImportDialogOpen}
        onOpenChange={setIsImportDialogOpen}
        onImport={handleImport}
      />
      
      {selectedItems.size > 0 && (
         <BulkBarcodeDialog
            isOpen={isBulkBarcodeDialogOpen}
            onOpenChange={setIsBulkBarcodeDialogOpen}
            items={selectedInventoryItems}
        />
      )}

      {printingItem && (
        <BarcodeDialog
          isOpen={!!printingItem}
          onOpenChange={() => setPrintingItem(null)}
          item={printingItem}
        />
      )}

      {adjustingItem && (
        <AdjustStockDialog
          isOpen={!!adjustingItem}
          onOpenChange={() => setAdjustingItem(null)}
          item={adjustingItem}
          onSubmit={handleAdjustStock}
        />
      )}
      
      <AlertDialog open={!!deletingItem} onOpenChange={() => setDeletingItem(null)}>
        <AlertDialogContent>
            <AlertDialogHeader>
                <AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
                <AlertDialogDescription>
                    This action cannot be undone. This will permanently delete {deletingItem?.id === 'bulk-delete' ? `the selected ${deletingItem.name}` : `the item: ${deletingItem?.name}`}.
                </AlertDialogDescription>
            </AlertDialogHeader>
            <AlertDialogFooter>
                <AlertDialogCancel>Cancel</AlertDialogCancel>
                <AlertDialogAction onClick={() => {
                    if (deletingItem?.id === 'bulk-delete') {
                        handleBulkDelete();
                    } else if (deletingItem) {
                        handleDelete(deletingItem);
                    }
                }}>Delete</AlertDialogAction>
            </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      <Card>
        <CardHeader>
          <CardTitle>Fabric & Materials</CardTitle>
          <CardDescription>
            Manage your fabric inventory and track stock levels.
          </CardDescription>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                 <TableHead className="w-[40px] pl-4">
                  <Checkbox
                    checked={selectedItems.size > 0 && selectedItems.size === filteredInventory.length}
                    onCheckedChange={(checked) => handleSelectAll(!!checked)}
                    aria-label="Select all"
                  />
                </TableHead>
                <TableHead className="hidden sm:table-cell">
                  Material ID
                </TableHead>
                <TableHead>Name</TableHead>
                <TableHead className="hidden md:table-cell">Type</TableHead>
                <TableHead className="hidden md:table-cell">Color</TableHead>
                <TableHead>Status</TableHead>
                <TableHead className="hidden sm:table-cell text-right">Quantity</TableHead>
                <TableHead className="text-right">Price/meter</TableHead>
                <TableHead>
                  <span className="sr-only">Actions</span>
                </TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredInventory.map((item) => {
                const status = getStockStatus(item);
                const isSelected = selectedItems.has(item.id);
                return (
                  <TableRow key={item.id} data-state={isSelected ? 'selected' : ''}>
                    <TableCell className="pl-4">
                        <Checkbox
                            checked={isSelected}
                            onCheckedChange={(checked) => handleSelectItem(item.id, !!checked)}
                            aria-label={`Select item ${item.name}`}
                        />
                    </TableCell>
                    <TableCell className="hidden sm:table-cell font-medium">
                      {item.id}
                    </TableCell>
                    <TableCell className="font-medium">{item.name}</TableCell>
                    <TableCell className="hidden md:table-cell">{item.type}</TableCell>
                    <TableCell className="hidden md:table-cell">{item.color}</TableCell>
                    <TableCell>
                      <Badge variant={status.variant}>{status.text}</Badge>
                    </TableCell>
                    <TableCell className="hidden sm:table-cell text-right">{item.quantity}m</TableCell>
                    <TableCell className="text-right">৳{item.pricePerMeter.toFixed(2)}</TableCell>
                    <TableCell>
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button aria-haspopup="true" size="icon" variant="ghost">
                            <MoreHorizontal className="h-4 w-4" />
                            <span className="sr-only">Toggle menu</span>
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end">
                          <DropdownMenuLabel>Actions</DropdownMenuLabel>
                          <DropdownMenuItem onClick={() => openEditDialog(item)}>Edit</DropdownMenuItem>
                          <DropdownMenuItem onClick={() => openAdjustStockDialog(item)}>Adjust Stock</DropdownMenuItem>
                          <DropdownMenuItem onClick={() => openPrintBarcodeDialog(item)}>Print Barcode</DropdownMenuItem>
                          <DropdownMenuItem className="text-red-600" onClick={() => openDeleteDialog(item)}>Delete</DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </TableCell>
                  </TableRow>
                );
              })}
            </TableBody>
          </Table>
        </CardContent>
        <CardFooter>
          <div className="text-xs text-muted-foreground">
            Showing <strong>1-{filteredInventory.length}</strong> of <strong>{inventory.length}</strong> items
          </div>
        </CardFooter>
      </Card>
    </div>
  );
}
