'use client';

import React, { useState, useEffect, useMemo } from 'react';
import { MoreHorizontal, Search, File, Upload, Trash2 } from "lucide-react";
import { z } from 'zod';

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 {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Input } from '@/components/ui/input';
import { PageHeader } from "@/components/page-header";
import { getMockTailoringItems, type TailoringItem } from "@/lib/data";
import { exportToCsv } from '@/lib/utils';
import { ItemDialog } from '@/components/items/item-dialog';
import { ItemFormValues } from '@/components/items/item-form';
import { ImportItemsDialog } from '@/components/items/import-items-dialog';

import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";


export default function ItemsPage() {
    const [items, setItems] = useState<TailoringItem[]>([]);
    const [searchTerm, setSearchTerm] = useState('');
    const [isDialogOpen, setIsDialogOpen] = useState(false);
    const [isImportDialogOpen, setIsImportDialogOpen] = useState(false);
    const [editingItem, setEditingItem] = useState<TailoringItem | null>(null);
    const [deletingItem, setDeletingItem] = useState<TailoringItem | null>(null);
    const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
    
    const loadData = () => {
        setItems(getMockTailoringItems());
    }

    useEffect(() => {
        loadData();
        window.addEventListener('storage', loadData);
        return () => window.removeEventListener('storage', loadData);
    }, []);
    

    const updateItems = (newItems: TailoringItem[]) => {
        setItems(newItems);
        localStorage.setItem('mockTailoringItems', JSON.stringify(newItems));
        setSelectedItems(new Set());
    };

    const handleFormSubmit = (data: ItemFormValues) => {
        if (editingItem) {
            const updatedItems = items.map(item => item.id === editingItem.id ? { ...item, ...data } : item);
            updateItems(updatedItems);
        } else {
            const newItem: TailoringItem = {
                id: `ITEM${(items.length + 1).toString().padStart(3, '0')}`,
                ...data,
            };
            updateItems([newItem, ...items]);
        }
        closeDialog();
    };

    const handleDelete = (item: TailoringItem) => {
        const newItems = items.filter(i => i.id !== item.id);
        updateItems(newItems);
        setDeletingItem(null);
    };

    const handleBulkDelete = () => {
      const newItems = items.filter(item => !selectedItems.has(item.id));
      updateItems(newItems);
      setDeletingItem(null);
    };
    
    const openAddDialog = () => {
        setEditingItem(null);
        setIsDialogOpen(true);
    };

    const openEditDialog = (item: TailoringItem) => {
        setEditingItem(item);
        setIsDialogOpen(true);
    };

    const openDeleteDialog = (item: TailoringItem) => {
        setDeletingItem(item);
    };

    const openBulkDeleteDialog = () => {
        setDeletingItem({ id: 'bulk-delete', name: `${selectedItems.size} items` } as any);
    }


    const closeDialog = () => {
        setIsDialogOpen(false);
        setEditingItem(null);
    }
    
    const handleSelectAll = (checked: boolean) => {
        if (checked) {
        setSelectedItems(new Set(filteredItems.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 handleExport = () => {
        exportToCsv(filteredItems, 'tailoring-items.csv');
    };
    
    const handleImport = (newItems: TailoringItem[]) => {
        const updatedItems = [...items];
        newItems.forEach(newItem => {
            const existingIndex = updatedItems.findIndex(i => i.id === newItem.id);
            if (existingIndex > -1) {
                updatedItems[existingIndex] = newItem;
            } else {
                updatedItems.push(newItem);
            }
        });
        updateItems(updatedItems);
        setIsImportDialogOpen(false);
    };

    const filteredItems = items.filter(item =>
        item.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        item.category.toLowerCase().includes(searchTerm.toLowerCase())
    );

  return (
    <div className="flex flex-col gap-4">
        <PageHeader title="Tailoring Items" actionButtonText="Add Item" 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 items..."
                    className="pl-8 w-full"
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                />
            </div>
             {selectedItems.size > 0 && (
                <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>
        
       <ItemDialog
            isOpen={isDialogOpen}
            onOpenChange={setIsDialogOpen}
            item={editingItem}
            onSubmit={handleFormSubmit}
        />
        
        <ImportItemsDialog
            isOpen={isImportDialogOpen}
            onOpenChange={setIsImportDialogOpen}
            onImport={handleImport}
        />

        <AlertDialog open={!!deletingItem} onOpenChange={() => setDeletingItem(null)}>
            <AlertDialogContent>
                <AlertDialogHeader>
                    <AlertDialogTitle>Are you 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>Item List</CardTitle>
            <CardDescription>
              A list of all tailoring items you offer.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-[40px] pl-4">
                    <Checkbox
                        checked={selectedItems.size > 0 && selectedItems.size === filteredItems.length}
                        onCheckedChange={(checked) => handleSelectAll(!!checked)}
                        aria-label="Select all"
                    />
                  </TableHead>
                  <TableHead className="hidden sm:table-cell">Item ID</TableHead>
                  <TableHead>Name</TableHead>
                  <TableHead className="hidden md:table-cell">Category</TableHead>
                  <TableHead className="text-right">Sewing Price</TableHead>
                  <TableHead className="text-right hidden sm:table-cell">Artisan Wage</TableHead>
                  <TableHead>
                    <span className="sr-only">Actions</span>
                  </TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredItems.map((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="font-medium hidden sm:table-cell">{item.id}</TableCell>
                        <TableCell className="font-medium">{item.name}</TableCell>
                        <TableCell className="hidden md:table-cell">{item.category}</TableCell>
                        <TableCell className="text-right">৳{(item.sewingPrice || 0).toFixed(2)}</TableCell>
                        <TableCell className="text-right hidden sm:table-cell">৳{(item.artisanWage || 0).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 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-{filteredItems.length}</strong> of <strong>{items.length}</strong> items
            </div>
          </CardFooter>
        </Card>
    </div>
  )
}
