'use client';

import React, { useState, useEffect } from 'react';
import { MoreHorizontal, Search, File, Upload, Trash2 } from "lucide-react"
import Link from 'next/link';
import { useRouter } from 'next/navigation';

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 { getMockCustomers, getMockOrders, type Customer, type Order } from "@/lib/data"
import { PageHeader } from "@/components/page-header"
import { Input } from '@/components/ui/input';
import { AddCustomerDialog } from '@/components/customers/add-customer-dialog';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { exportToCsv } from '@/lib/utils';
import { ImportCustomersDialog } from '@/components/customers/import-customers-dialog';


export default function CustomersPage() {
    const [customers, setCustomers] = useState<Customer[]>([]);
    const [orders, setOrders] = useState<Order[]>([]);
    const [searchTerm, setSearchTerm] = useState('');
    const [isAddCustomerOpen, setIsAddCustomerOpen] = useState(false);
    const [isImportDialogOpen, setIsImportDialogOpen] = useState(false);
    const [deletingCustomer, setDeletingCustomer] = useState<Customer | null>(null);
    const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
    const router = useRouter();

    const loadData = () => {
        setCustomers(getMockCustomers());
        setOrders(getMockOrders());
    };
    
    useEffect(() => {
        loadData();
        window.addEventListener('storage', loadData);
        return () => window.removeEventListener('storage', loadData);
    }, []);
    
    const updateCustomers = (newCustomers: Customer[]) => {
        setCustomers(newCustomers);
        localStorage.setItem('mockCustomers', JSON.stringify(newCustomers));
        setSelectedItems(new Set());
    };

    const handleAddCustomer = (newCustomerData: Omit<Customer, 'id'>) => {
        const newCustomer: Customer = {
            id: `CUST${(customers.length + 1).toString().padStart(3, '0')}`,
            ...newCustomerData,
        };
        updateCustomers([newCustomer, ...customers]);
    };

    const handleDeleteCustomer = (customer: Customer) => {
        const newCustomers = customers.filter(c => c.id !== customer.id);
        updateCustomers(newCustomers);
        setDeletingCustomer(null);
    };

    const handleBulkDelete = () => {
        const newCustomers = customers.filter(customer => !selectedItems.has(customer.id));
        updateCustomers(newCustomers);
        setDeletingCustomer(null); 
    };

    const openDeleteDialog = (customer: Customer) => {
        setDeletingCustomer(customer);
    };

    const openBulkDeleteDialog = () => {
        setDeletingCustomer({ id: 'bulk-delete', name: `${selectedItems.size} customers` } as any);
    };
    
    const handleExport = () => {
        exportToCsv(filteredCustomers, 'customers.csv');
    };
    
    const handleImport = (newItems: Customer[]) => {
        const updatedCustomers = [...customers];
        newItems.forEach(newItem => {
            const existingIndex = updatedCustomers.findIndex(i => i.id === newItem.id);
            if (existingIndex > -1) {
                updatedCustomers[existingIndex] = newItem;
            } else {
                updatedCustomers.push(newItem);
            }
        });
        updateCustomers(updatedCustomers);
        setIsImportDialogOpen(false);
    };

    const handleSelectAll = (checked: boolean) => {
        if (checked) {
          setSelectedItems(new Set(filteredCustomers.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 filteredCustomers = customers.filter(customer =>
        customer.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        customer.phone.includes(searchTerm)
    );

    const getCustomerOrderStats = (customerId: string) => {
        const customerOrders = orders
            .filter(order => order.customerId === customerId && order.status !== 'Cancelled')
            .sort((a,b) => new Date(b.date).getTime() - new Date(a.date).getTime());
            
        const totalOrders = customerOrders.length;
        const totalSpent = customerOrders.reduce((sum, order) => sum + (order.paidAmount || 0), 0);
        const latestOrder = totalOrders > 0 ? customerOrders[0] : null;

        return { totalOrders, totalSpent, latestOrder };
    }

  return (
    <div className="flex flex-col gap-4">
        <PageHeader title="Customers" actionButtonText="Add Customer" onActionButtonClick={() => setIsAddCustomerOpen(true)}>
            <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 customers..."
                    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>
        <AddCustomerDialog
            isOpen={isAddCustomerOpen}
            onOpenChange={setIsAddCustomerOpen}
            onCustomerAdd={handleAddCustomer}
        />
        <ImportCustomersDialog
            isOpen={isImportDialogOpen}
            onOpenChange={setIsImportDialogOpen}
            onImport={handleImport}
        />
        <AlertDialog open={!!deletingCustomer} onOpenChange={() => setDeletingCustomer(null)}>
            <AlertDialogContent>
                <AlertDialogHeader>
                    <AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
                    <AlertDialogDescription>
                         This action cannot be undone. This will permanently delete {deletingCustomer?.id === 'bulk-delete' ? `the selected ${deletingCustomer.name}` : `the customer: ${deletingCustomer?.name}`}.
                    </AlertDialogDescription>
                </AlertDialogHeader>
                <AlertDialogFooter>
                    <AlertDialogCancel>Cancel</AlertDialogCancel>
                    <AlertDialogAction onClick={() => {
                        if (deletingCustomer?.id === 'bulk-delete') {
                            handleBulkDelete();
                        } else if (deletingCustomer) {
                            handleDeleteCustomer(deletingCustomer);
                        }
                    }}>Delete</AlertDialogAction>
                </AlertDialogFooter>
            </AlertDialogContent>
       </AlertDialog>
        <Card>
          <CardHeader>
            <CardTitle>Customer Database</CardTitle>
            <CardDescription>
              A list of all customers in your database.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <Table>
              <TableHeader>
                <TableRow>
                   <TableHead className="w-[40px] pl-4">
                    <Checkbox
                        checked={selectedItems.size > 0 && selectedItems.size === filteredCustomers.length}
                        onCheckedChange={(checked) => handleSelectAll(!!checked)}
                        aria-label="Select all"
                    />
                  </TableHead>
                  <TableHead className="hidden sm:table-cell">Customer ID</TableHead>
                  <TableHead>Name</TableHead>
                  <TableHead className="hidden md:table-cell">Phone</TableHead>
                  <TableHead className="hidden lg:table-cell">
                    Orders (Latest Items)
                  </TableHead>
                  <TableHead className="text-right">Total Spent</TableHead>
                  <TableHead>
                    <span className="sr-only">Actions</span>
                  </TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredCustomers.map((customer) => {
                    const { totalOrders, totalSpent, latestOrder } = getCustomerOrderStats(customer.id);
                    const isSelected = selectedItems.has(customer.id);
                    return (
                        <TableRow key={customer.id} data-state={isSelected ? 'selected' : ''}>
                             <TableCell className="pl-4">
                                <Checkbox
                                    checked={isSelected}
                                    onCheckedChange={(checked) => handleSelectItem(customer.id, !!checked)}
                                    aria-label={`Select item ${customer.name}`}
                                />
                            </TableCell>
                            <TableCell className="hidden sm:table-cell font-medium">
                                {customer.id}
                            </TableCell>
                            <TableCell>
                                <Link href={`/dashboard/customers/${customer.id}`} className="font-medium hover:underline">{customer.name}</Link>
                                <div className="text-sm text-muted-foreground md:hidden">{customer.phone}</div>
                            </TableCell>
                            <TableCell className="hidden md:table-cell">
                                {customer.phone}
                            </TableCell>
                            <TableCell className="hidden lg:table-cell">
                                <div className="font-medium">{totalOrders} order(s)</div>
                                {latestOrder && (
                                    <div className="text-xs text-muted-foreground truncate max-w-xs">
                                        {latestOrder.items.map(item => `${item.name} (x${item.quantity})`).join(', ')}
                                    </div>
                                )}
                            </TableCell>
                            <TableCell className="text-right">৳{totalSpent.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={() => router.push(`/dashboard/customers/${customer.id}`)}>View Profile</DropdownMenuItem>
                                    <DropdownMenuItem className="text-red-600" onClick={() => openDeleteDialog(customer)}>Delete</DropdownMenuItem>
                                </DropdownMenuContent>
                                </DropdownMenu>
                            </TableCell>
                        </TableRow>
                    )
                })}
              </TableBody>
            </Table>
          </CardContent>
          <CardFooter>
            <div className="text-xs text-muted-foreground">
              Showing <strong>1-{filteredCustomers.length}</strong> of <strong>{customers.length}</strong> customers
            </div>
          </CardFooter>
        </Card>
    </div>
  )
}
