'use client';
import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { Receipt, Plus, Trash2, ArrowLeft, Calculator } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Separator } from '@/components/ui/separator';
import { toast } from 'sonner';
import Link from 'next/link';

interface InvoiceItem {
  productId: string; name: string; description: string; quantity: string; price: string; taxRate: string; hsnCode: string;
}

const emptyItem: InvoiceItem = { productId: '', name: '', description: '', quantity: '1', price: '0', taxRate: '18', hsnCode: '' };

export function NewInvoicePage() {
  const router = useRouter();
  const [customers, setCustomers] = useState<any[]>([]);
  const [products, setProducts] = useState<any[]>([]);
  const [customerId, setCustomerId] = useState('');
  const [items, setItems] = useState<InvoiceItem[]>([{ ...emptyItem }]);
  const [discount, setDiscount] = useState('0');
  const [notes, setNotes] = useState('');
  const [dueDate, setDueDate] = useState('');
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    fetch('/api/customers').then(r => r.json()).then(d => setCustomers(Array.isArray(d) ? d : [])).catch(() => {});
    fetch('/api/products').then(r => r.json()).then(d => setProducts(Array.isArray(d) ? d : [])).catch(() => {});
  }, []);

  const updateItem = (index: number, field: string, value: string) => {
    const newItems = [...(items ?? [])];
    if (newItems[index]) {
      (newItems[index] as any)[field] = value;
    }
    setItems(newItems);
  };

  const addProduct = (index: number, productId: string) => {
    const product = (products ?? []).find((p: any) => p?.id === productId);
    if (product) {
      const newItems = [...(items ?? [])];
      if (newItems[index]) {
        newItems[index] = {
          productId: product.id,
          name: product?.name ?? '',
          description: product?.description ?? '',
          quantity: '1',
          price: String(product?.price ?? '0'),
          taxRate: String(product?.taxRate ?? '18'),
          hsnCode: product?.hsnCode ?? '',
        };
      }
      setItems(newItems);
    }
  };

  const addItem = () => setItems([...(items ?? []), { ...emptyItem }]);
  const removeItem = (index: number) => {
    if ((items?.length ?? 0) <= 1) return;
    setItems((items ?? []).filter((_: any, i: number) => i !== index));
  };

  const subtotal = (items ?? []).reduce((sum: number, item: InvoiceItem) => {
    return sum + (parseFloat(item?.quantity ?? '0') || 0) * (parseFloat(item?.price ?? '0') || 0);
  }, 0);

  const taxAmount = (items ?? []).reduce((sum: number, item: InvoiceItem) => {
    const amt = (parseFloat(item?.quantity ?? '0') || 0) * (parseFloat(item?.price ?? '0') || 0);
    return sum + amt * ((parseFloat(item?.taxRate ?? '0') || 0) / 100);
  }, 0);

  const total = subtotal + taxAmount - (parseFloat(discount ?? '0') || 0);

  const handleSubmit = async (asDraft: boolean = true) => {
    if (!customerId) { toast.error('Please select a customer'); return; }
    const validItems = (items ?? []).filter((i: InvoiceItem) => i?.name && parseFloat(i?.price ?? '0') > 0);
    if (validItems.length === 0) { toast.error('Add at least one item'); return; }
    setSaving(true);
    try {
      const res = await fetch('/api/invoices', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          customerId,
          items: validItems,
          discount: parseFloat(discount ?? '0') || 0,
          notes,
          dueDate: dueDate || null,
          status: asDraft ? 'DRAFT' : 'SENT',
        }),
      });
      if (!res.ok) { const d = await res.json(); toast.error(d?.error || 'Failed'); return; }
      const invoice = await res.json();
      toast.success('Invoice created!');
      router.push(`/dashboard/invoices/${invoice?.id ?? ''}`);
    } catch { toast.error('Failed to create invoice'); } finally { setSaving(false); }
  };

  return (
    <div className="max-w-[1000px] mx-auto">
      <div className="flex items-center gap-3 mb-6">
        <Link href="/dashboard/invoices"><Button variant="ghost" size="icon"><ArrowLeft className="w-5 h-5" /></Button></Link>
        <div>
          <h1 className="font-display text-2xl font-bold tracking-tight flex items-center gap-2"><Receipt className="w-6 h-6 text-primary" /> New Invoice</h1>
          <p className="text-muted-foreground text-sm">Create a new invoice for your customer</p>
        </div>
      </div>

      <div className="grid lg:grid-cols-3 gap-6">
        <div className="lg:col-span-2 space-y-6">
          {/* Customer Selection */}
          <Card>
            <CardHeader><CardTitle className="text-base">Customer</CardTitle></CardHeader>
            <CardContent>
              <Select value={customerId} onValueChange={setCustomerId}>
                <SelectTrigger><SelectValue placeholder="Select a customer" /></SelectTrigger>
                <SelectContent>
                  {(customers ?? []).map((c: any) => (
                    <SelectItem key={c?.id} value={c?.id ?? ''}>{c?.name ?? ''} ({c?.email ?? ''})</SelectItem>
                  ))}
                </SelectContent>
              </Select>
              {(customers?.length ?? 0) === 0 && <p className="text-sm text-muted-foreground mt-2">No customers yet. <Link href="/dashboard/customers" className="text-primary">Add one first</Link></p>}
            </CardContent>
          </Card>

          {/* Items */}
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <CardTitle className="text-base">Items</CardTitle>
                <Button variant="outline" size="sm" onClick={addItem}><Plus className="w-4 h-4 mr-1" /> Add Item</Button>
              </div>
            </CardHeader>
            <CardContent className="space-y-4">
              {(items ?? []).map((item: InvoiceItem, index: number) => (
                <div key={index} className="p-4 bg-muted/50 rounded-lg space-y-3">
                  <div className="flex items-center justify-between">
                    <Label className="text-xs text-muted-foreground">Item {index + 1}</Label>
                    <div className="flex gap-2">
                      <Select onValueChange={(v: string) => addProduct(index, v)}>
                        <SelectTrigger className="w-48 h-8 text-xs"><SelectValue placeholder="Pick from catalog" /></SelectTrigger>
                        <SelectContent>
                          {(products ?? []).map((p: any) => (
                            <SelectItem key={p?.id} value={p?.id ?? ''}>{p?.name ?? ''} (₹{p?.price ?? 0})</SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                      {(items?.length ?? 0) > 1 && <Button variant="ghost" size="icon" className="h-8 w-8 text-destructive" onClick={() => removeItem(index)}><Trash2 className="w-4 h-4" /></Button>}
                    </div>
                  </div>
                  <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
                    <div className="col-span-2"><Input placeholder="Item name" value={item?.name ?? ''} onChange={(e: any) => updateItem(index, 'name', e?.target?.value ?? '')} /></div>
                    <div><Input type="number" placeholder="Qty" value={item?.quantity ?? ''} onChange={(e: any) => updateItem(index, 'quantity', e?.target?.value ?? '')} /></div>
                    <div><Input type="number" step="0.01" placeholder="Price" value={item?.price ?? ''} onChange={(e: any) => updateItem(index, 'price', e?.target?.value ?? '')} /></div>
                  </div>
                  <div className="grid grid-cols-3 gap-3">
                    <div><Input placeholder="HSN Code" value={item?.hsnCode ?? ''} onChange={(e: any) => updateItem(index, 'hsnCode', e?.target?.value ?? '')} /></div>
                    <div><Input type="number" step="0.01" placeholder="Tax %" value={item?.taxRate ?? ''} onChange={(e: any) => updateItem(index, 'taxRate', e?.target?.value ?? '')} /></div>
                    <div className="flex items-center text-sm font-mono font-semibold text-primary">
                      ₹{((parseFloat(item?.quantity ?? '0') || 0) * (parseFloat(item?.price ?? '0') || 0))?.toFixed?.(2) ?? '0.00'}
                    </div>
                  </div>
                </div>
              ))}
            </CardContent>
          </Card>

          {/* Notes */}
          <Card>
            <CardHeader><CardTitle className="text-base">Additional Details</CardTitle></CardHeader>
            <CardContent className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div><Label>Due Date</Label><Input type="date" value={dueDate} onChange={(e: any) => setDueDate(e?.target?.value ?? '')} className="mt-1" /></div>
                <div><Label>Discount (₹)</Label><Input type="number" step="0.01" value={discount} onChange={(e: any) => setDiscount(e?.target?.value ?? '0')} className="mt-1" /></div>
              </div>
              <div><Label>Notes</Label><Textarea value={notes} onChange={(e: any) => setNotes(e?.target?.value ?? '')} placeholder="Payment terms, notes..." className="mt-1" rows={3} /></div>
            </CardContent>
          </Card>
        </div>

        {/* Summary */}
        <div>
          <Card className="sticky top-24">
            <CardHeader><CardTitle className="text-base flex items-center gap-2"><Calculator className="w-4 h-4" /> Summary</CardTitle></CardHeader>
            <CardContent className="space-y-3">
              <div className="flex justify-between text-sm"><span className="text-muted-foreground">Subtotal</span><span className="font-mono">₹{subtotal?.toFixed?.(2) ?? '0.00'}</span></div>
              <div className="flex justify-between text-sm"><span className="text-muted-foreground">Tax</span><span className="font-mono">₹{taxAmount?.toFixed?.(2) ?? '0.00'}</span></div>
              {(parseFloat(discount ?? '0') || 0) > 0 && <div className="flex justify-between text-sm"><span className="text-muted-foreground">Discount</span><span className="font-mono text-destructive">-₹{(parseFloat(discount ?? '0') || 0)?.toFixed?.(2) ?? '0.00'}</span></div>}
              <Separator />
              <div className="flex justify-between font-bold text-lg"><span>Total</span><span className="font-mono text-primary">₹{total?.toFixed?.(2) ?? '0.00'}</span></div>
              <div className="space-y-2 pt-4">
                <Button className="w-full" onClick={() => handleSubmit(true)} disabled={saving}>{saving ? 'Saving...' : 'Save as Draft'}</Button>
                <Button variant="outline" className="w-full" onClick={() => handleSubmit(false)} disabled={saving}>Save & Send</Button>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}
