'use client';
import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { Users, Plus, Search, Edit, Trash2, X, Mail, Phone, MapPin, Building2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardContent } from '@/components/ui/card';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { toast } from 'sonner';

interface Customer {
  id: string;
  name: string;
  email: string;
  phone: string | null;
  address: string | null;
  gstNumber: string | null;
  city: string | null;
  state: string | null;
  pincode: string | null;
}

const emptyCustomer = { name: '', email: '', phone: '', address: '', gstNumber: '', city: '', state: '', pincode: '' };

export function CustomersPage() {
  const [customers, setCustomers] = useState<Customer[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [showDialog, setShowDialog] = useState(false);
  const [editing, setEditing] = useState<Customer | null>(null);
  const [form, setForm] = useState(emptyCustomer);
  const [saving, setSaving] = useState(false);

  const fetchCustomers = async () => {
    try {
      const res = await fetch('/api/customers');
      const data = await res.json();
      setCustomers(Array.isArray(data) ? data : []);
    } catch { setCustomers([]); }
    setLoading(false);
  };

  useEffect(() => { fetchCustomers(); }, []);

  const filtered = (customers ?? []).filter((c: Customer) =>
    (c?.name ?? '').toLowerCase().includes((search ?? '').toLowerCase()) ||
    (c?.email ?? '').toLowerCase().includes((search ?? '').toLowerCase())
  );

  const openAdd = () => { setEditing(null); setForm(emptyCustomer); setShowDialog(true); };
  const openEdit = (c: Customer) => {
    setEditing(c);
    setForm({ name: c?.name ?? '', email: c?.email ?? '', phone: c?.phone ?? '', address: c?.address ?? '', gstNumber: c?.gstNumber ?? '', city: c?.city ?? '', state: c?.state ?? '', pincode: c?.pincode ?? '' });
    setShowDialog(true);
  };

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!form?.name || !form?.email) { toast.error('Name and email are required'); return; }
    setSaving(true);
    try {
      const url = editing ? `/api/customers/${editing.id}` : '/api/customers';
      const method = editing ? 'PUT' : 'POST';
      const res = await fetch(url, { method, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(form) });
      if (!res.ok) { const d = await res.json(); toast.error(d?.error || 'Failed'); return; }
      toast.success(editing ? 'Customer updated' : 'Customer added');
      setShowDialog(false);
      fetchCustomers();
    } catch { toast.error('Failed to save'); } finally { setSaving(false); }
  };

  const handleDelete = async (id: string) => {
    if (!confirm('Delete this customer?')) return;
    try {
      await fetch(`/api/customers/${id}`, { method: 'DELETE' });
      toast.success('Customer deleted');
      fetchCustomers();
    } catch { toast.error('Failed to delete'); }
  };

  return (
    <div className="max-w-[1200px] mx-auto">
      <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between mb-6 gap-4">
        <div>
          <h1 className="font-display text-2xl font-bold tracking-tight flex items-center gap-2"><Users className="w-6 h-6 text-primary" /> Customers</h1>
          <p className="text-muted-foreground text-sm mt-1">Manage your client database</p>
        </div>
        <Button onClick={openAdd}><Plus className="w-4 h-4 mr-2" /> Add Customer</Button>
      </div>

      <div className="relative mb-6">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
        <Input placeholder="Search customers..." value={search} onChange={(e: any) => setSearch(e?.target?.value ?? '')} className="pl-10 max-w-sm" />
      </div>

      {loading ? (
        <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-4">{[1,2,3].map(i => <div key={i} className="h-40 bg-muted rounded-xl animate-pulse" />)}</div>
      ) : filtered.length === 0 ? (
        <Card><CardContent className="py-12 text-center">
          <Users className="w-12 h-12 mx-auto mb-3 text-muted-foreground/50" />
          <p className="text-muted-foreground">No customers found</p>
          <Button onClick={openAdd} className="mt-4" size="sm">Add Your First Customer</Button>
        </CardContent></Card>
      ) : (
        <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-4">
          {filtered.map((c: Customer, i: number) => (
            <motion.div key={c?.id} initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: i * 0.05 }}>
              <Card className="hover:shadow-md transition-shadow">
                <CardContent className="p-5">
                  <div className="flex items-start justify-between mb-3">
                    <div className="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary font-bold text-sm">
                      {(c?.name ?? '?')?.[0]?.toUpperCase?.() ?? '?'}
                    </div>
                    <div className="flex gap-1">
                      <button onClick={() => openEdit(c)} className="p-1.5 rounded-md hover:bg-muted text-muted-foreground hover:text-foreground"><Edit className="w-4 h-4" /></button>
                      <button onClick={() => handleDelete(c?.id ?? '')} className="p-1.5 rounded-md hover:bg-destructive/10 text-muted-foreground hover:text-destructive"><Trash2 className="w-4 h-4" /></button>
                    </div>
                  </div>
                  <h3 className="font-medium mb-1">{c?.name ?? ''}</h3>
                  <div className="space-y-1 text-sm text-muted-foreground">
                    <p className="flex items-center gap-1.5"><Mail className="w-3.5 h-3.5" /> {c?.email ?? ''}</p>
                    {c?.phone ? <p className="flex items-center gap-1.5"><Phone className="w-3.5 h-3.5" /> {c.phone}</p> : null}
                    {c?.city || c?.state ? <p className="flex items-center gap-1.5"><MapPin className="w-3.5 h-3.5" /> {[c?.city, c?.state].filter(Boolean).join(', ')}</p> : null}
                    {c?.gstNumber ? <p className="flex items-center gap-1.5"><Building2 className="w-3.5 h-3.5" /> {c.gstNumber}</p> : null}
                  </div>
                </CardContent>
              </Card>
            </motion.div>
          ))}
        </div>
      )}

      <Dialog open={showDialog} onOpenChange={setShowDialog}>
        <DialogContent className="max-w-md">
          <DialogHeader><DialogTitle>{editing ? 'Edit Customer' : 'Add Customer'}</DialogTitle></DialogHeader>
          <form onSubmit={handleSave} className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div className="col-span-2"><Label>Name *</Label><Input value={form?.name ?? ''} onChange={(e: any) => setForm({...(form ?? emptyCustomer), name: e?.target?.value ?? ''})} placeholder="Customer name" className="mt-1" /></div>
              <div className="col-span-2"><Label>Email *</Label><Input type="email" value={form?.email ?? ''} onChange={(e: any) => setForm({...(form ?? emptyCustomer), email: e?.target?.value ?? ''})} placeholder="email@example.com" className="mt-1" /></div>
              <div><Label>Phone</Label><Input value={form?.phone ?? ''} onChange={(e: any) => setForm({...(form ?? emptyCustomer), phone: e?.target?.value ?? ''})} placeholder="Phone" className="mt-1" /></div>
              <div><Label>GST Number</Label><Input value={form?.gstNumber ?? ''} onChange={(e: any) => setForm({...(form ?? emptyCustomer), gstNumber: e?.target?.value ?? ''})} placeholder="GST" className="mt-1" /></div>
              <div className="col-span-2"><Label>Address</Label><Input value={form?.address ?? ''} onChange={(e: any) => setForm({...(form ?? emptyCustomer), address: e?.target?.value ?? ''})} placeholder="Address" className="mt-1" /></div>
              <div><Label>City</Label><Input value={form?.city ?? ''} onChange={(e: any) => setForm({...(form ?? emptyCustomer), city: e?.target?.value ?? ''})} placeholder="City" className="mt-1" /></div>
              <div><Label>State</Label><Input value={form?.state ?? ''} onChange={(e: any) => setForm({...(form ?? emptyCustomer), state: e?.target?.value ?? ''})} placeholder="State" className="mt-1" /></div>
              <div><Label>Pincode</Label><Input value={form?.pincode ?? ''} onChange={(e: any) => setForm({...(form ?? emptyCustomer), pincode: e?.target?.value ?? ''})} placeholder="Pincode" className="mt-1" /></div>
            </div>
            <div className="flex justify-end gap-2">
              <Button type="button" variant="outline" onClick={() => setShowDialog(false)}>Cancel</Button>
              <Button type="submit" disabled={saving}>{saving ? 'Saving...' : editing ? 'Update' : 'Add Customer'}</Button>
            </div>
          </form>
        </DialogContent>
      </Dialog>
    </div>
  );
}
