'use client';

import React, { useState, useEffect, useMemo } from 'react';
import { useRouter, useParams } from 'next/navigation';
import { ChevronsLeft, Phone, User, ShoppingBag, Banknote, MoreHorizontal, FileText } from 'lucide-react';

import { 
    getMockCustomers, 
    getMockOrders, 
    getMockMeasurements,
    addMockMeasurement,
    updateMockMeasurement,
    deleteMockMeasurement,
    getMockTailoringItems,
    type Customer, 
    type Order, 
    type CustomerMeasurement,
    type TailoringItem 
} from '@/lib/data';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { PageHeader } from '@/components/page-header';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { MeasurementDialog } from '@/components/customers/measurement-dialog';
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 { Badge } from '@/components/ui/badge';

export default function CustomerProfilePage() {
  const router = useRouter();
  const params = useParams();
  const { id } = params;

  const [customer, setCustomer] = useState<Customer | null>(null);
  const [orders, setOrders] = useState<Order[]>([]);
  const [measurements, setMeasurements] = useState<CustomerMeasurement[]>([]);
  const [tailoringItems, setTailoringItems] = useState<TailoringItem[]>([]);

  const [isMeasurementDialogOpen, setIsMeasurementDialogOpen] = useState(false);
  const [editingMeasurement, setEditingMeasurement] = useState<CustomerMeasurement | null>(null);
  const [deletingMeasurement, setDeletingMeasurement] = useState<CustomerMeasurement | null>(null);

  const customerId = typeof id === 'string' ? id : '';

  const loadData = () => {
      const allCustomers = getMockCustomers();
      const foundCustomer = allCustomers.find(c => c.id === customerId) || null;
      setCustomer(foundCustomer);

      if (foundCustomer) {
        const allOrders = getMockOrders();
        const customerOrders = allOrders.filter(o => o.customerId === foundCustomer.id);
        setOrders(customerOrders);

        const customerMeasurements = getMockMeasurements(foundCustomer.id);
        setMeasurements(customerMeasurements);
      }
      
      setTailoringItems(getMockTailoringItems());
  };

  useEffect(() => {
    if (customerId) {
      loadData();
    }
     window.addEventListener('storage', loadData);
     return () => window.removeEventListener('storage', loadData);
  }, [customerId]);
  
  const { totalOrders, totalSpent } = useMemo(() => {
    const customerOrders = orders.filter(order => order.status !== 'Cancelled');
    const total = customerOrders.reduce((sum, order) => sum + (order.paidAmount || 0), 0);
    return { totalOrders: customerOrders.length, totalSpent: total };
  }, [orders]);

  const handleMeasurementSubmit = (data: { itemName: string, measurements: string }) => {
    if (editingMeasurement) {
        updateMockMeasurement({ ...editingMeasurement, ...data });
    } else {
        addMockMeasurement({ customerId, ...data });
    }
    loadData();
    closeMeasurementDialog();
  };

  const openAddMeasurementDialog = () => {
    setEditingMeasurement(null);
    setIsMeasurementDialogOpen(true);
  };

  const openEditMeasurementDialog = (measurement: CustomerMeasurement) => {
    setEditingMeasurement(measurement);
    setIsMeasurementDialogOpen(true);
  };

  const openDeleteMeasurementDialog = (measurement: CustomerMeasurement) => {
    setDeletingMeasurement(measurement);
  };

  const handleDeleteMeasurement = () => {
    if (deletingMeasurement) {
        deleteMockMeasurement(deletingMeasurement.id);
        loadData();
        setDeletingMeasurement(null);
    }
  };

  const closeMeasurementDialog = () => {
    setIsMeasurementDialogOpen(false);
    setEditingMeasurement(null);
  };

  if (!customer) {
    return (
      <div className="flex justify-center items-center h-full">
        <p>Customer not found.</p>
        <Button onClick={() => router.push('/dashboard/customers')} className="mt-4 ml-4">
            Go Back
        </Button>
      </div>
    );
  }

  const getStatusBadgeVariant = (status: Order['status']) => {
    switch (status) {
        case "Completed": return "success" as const;
        case "In Progress":
        case "Ready for Delivery": return "secondary" as const;
        case "Cancelled": return "destructive" as const;
        default: return "outline" as const;
    }
  }

  return (
    <div className="flex flex-col gap-4">
        <MeasurementDialog
            isOpen={isMeasurementDialogOpen}
            onOpenChange={setIsMeasurementDialogOpen}
            measurement={editingMeasurement}
            onSubmit={handleMeasurementSubmit}
            tailoringItems={tailoringItems}
        />
        <AlertDialog open={!!deletingMeasurement} onOpenChange={() => setDeletingMeasurement(null)}>
            <AlertDialogContent>
                <AlertDialogHeader>
                    <AlertDialogTitle>Are you sure?</AlertDialogTitle>
                    <AlertDialogDescription>
                        This will permanently delete this measurement record. This action cannot be undone.
                    </AlertDialogDescription>
                </AlertDialogHeader>
                <AlertDialogFooter>
                    <AlertDialogCancel>Cancel</AlertDialogCancel>
                    <AlertDialogAction onClick={handleDeleteMeasurement}>Delete</AlertDialogAction>
                </AlertDialogFooter>
            </AlertDialogContent>
       </AlertDialog>

      <PageHeader title={`${customer.name}'s Profile`}>
        <Button variant="outline" onClick={() => router.push('/dashboard/customers')}>
          <ChevronsLeft className="mr-2 h-4 w-4" />
          Back to Customers
        </Button>
      </PageHeader>
      
      <div className="grid gap-4 md:grid-cols-3">
         <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">Contact Info</CardTitle>
                <User className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
                <div className="text-xl font-bold">{customer.name}</div>
                <p className="text-xs text-muted-foreground">{customer.phone}</p>
            </CardContent>
        </Card>
         <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">Total Orders</CardTitle>
                <ShoppingBag className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
                <div className="text-2xl font-bold">{totalOrders}</div>
                <p className="text-xs text-muted-foreground">Total orders placed</p>
            </CardContent>
        </Card>
        <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">Total Spent</CardTitle>
                <Banknote className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
                <div className="text-2xl font-bold">৳{totalSpent.toFixed(2)}</div>
                <p className="text-xs text-muted-foreground">Total amount spent on all orders</p>
            </CardContent>
        </Card>
      </div>

      <Card>
          <CardHeader>
            <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2">
                <div>
                    <CardTitle>Saved Measurements</CardTitle>
                    <CardDescription>
                        All saved measurements for this customer.
                    </CardDescription>
                </div>
                <Button onClick={openAddMeasurementDialog}>Add Measurement</Button>
            </div>
          </CardHeader>
          <CardContent>
            <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Item Name</TableHead>
                    <TableHead>Measurements</TableHead>
                    <TableHead className="text-right">
                        <span className="sr-only">Actions</span>
                    </TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {measurements.length > 0 ? measurements.map(m => (
                    <TableRow key={m.id}>
                      <TableCell className="font-medium">{m.itemName}</TableCell>
                      <TableCell className="whitespace-pre-line">{m.measurements}</TableCell>
                      <TableCell className="text-right">
                          <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={() => openEditMeasurementDialog(m)}>Edit</DropdownMenuItem>
                                <DropdownMenuItem className="text-red-600" onClick={() => openDeleteMeasurementDialog(m)}>Delete</DropdownMenuItem>
                            </DropdownMenuContent>
                            </DropdownMenu>
                      </TableCell>
                    </TableRow>
                  )) : (
                    <TableRow>
                      <TableCell colSpan={3} className="text-center h-24">No measurements saved for this customer.</TableCell>
                    </TableRow>
                  )}
                </TableBody>
              </Table>
          </CardContent>
      </Card>
      <Card>
          <CardHeader>
            <CardTitle>Recent Orders</CardTitle>
            <CardDescription>
                A list of all orders placed by this customer.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Order / Memo ID</TableHead>
                    <TableHead>Items</TableHead>
                    <TableHead>Delivery Date</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead className="text-right">Amount</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {orders.length > 0 ? orders.map(order => (
                    <TableRow key={order.id}>
                      <TableCell>
                        <div className="font-medium">{order.id}</div>
                        {order.memoId && <div className="text-sm text-muted-foreground">M: {order.memoId}</div>}
                        <div className="text-sm text-muted-foreground">{new Date(order.date).toLocaleDateString()}</div>
                      </TableCell>
                      <TableCell>
                        {order.items.map(item => (
                          <div key={item.id} className="mb-1 last:mb-0">
                            <span className="font-medium">{item.name} (x{item.quantity})</span>
                            {item.measurements && <p className="text-xs text-muted-foreground whitespace-pre-line">{item.measurements}</p>}
                          </div>
                        ))}
                      </TableCell>
                      <TableCell>{order.deliveryDate ? new Date(order.deliveryDate).toLocaleDateString() : 'N/A'}</TableCell>
                      <TableCell>
                          <Badge variant={getStatusBadgeVariant(order.status)}>{order.status}</Badge>
                      </TableCell>
                      <TableCell className="text-right">৳{order.totalAmount.toFixed(2)}</TableCell>
                    </TableRow>
                  )) : (
                    <TableRow>
                      <TableCell colSpan={5} className="text-center h-24">No orders found for this customer.</TableCell>
                    </TableRow>
                  )}
                </TableBody>
              </Table>
          </CardContent>
      </Card>
    </div>
  );
}
