'use client';

import { useState, useMemo, useCallback } from 'react';
import { motion } from 'framer-motion';
import Link from 'next/link';
import {
  ArrowLeft, FileText, Plus, Trash2, Download, Loader2, DollarSign
} from 'lucide-react';

interface LineItem {
  id: string;
  description: string;
  quantity: number;
  rate: number;
}

const CURRENCIES = [
  { code: 'USD', symbol: '$', label: 'USD ($)' },
  { code: 'EUR', symbol: '\u20ac', label: 'EUR (\u20ac)' },
  { code: 'GBP', symbol: '\u00a3', label: 'GBP (\u00a3)' },
];

function uid() {
  return Math.random().toString(36).slice(2, 9);
}

export default function InvoiceForgePage() {
  const [invoiceNumber, setInvoiceNumber] = useState('INV-001');
  const [date, setDate] = useState(() => new Date().toISOString().split('T')[0]);
  const [dueDate, setDueDate] = useState(() => {
    const d = new Date();
    d.setDate(d.getDate() + 30);
    return d.toISOString().split('T')[0];
  });
  const [currency, setCurrency] = useState('USD');
  const [taxRate, setTaxRate] = useState(0);
  const [discount, setDiscount] = useState(0);
  const [notes, setNotes] = useState('Payment is due within 30 days. Thank you for your business.');

  const [from, setFrom] = useState({ name: '', address: '', email: '' });
  const [to, setTo] = useState({ name: '', company: '', address: '', email: '' });

  const [items, setItems] = useState<LineItem[]>([
    { id: uid(), description: '', quantity: 1, rate: 0 },
  ]);

  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const sym = CURRENCIES.find(c => c.code === currency)?.symbol || '$';

  const subtotal = useMemo(() => items.reduce((s, i) => s + i.quantity * i.rate, 0), [items]);
  const discountAmount = subtotal * (discount / 100);
  const afterDiscount = subtotal - discountAmount;
  const taxAmount = afterDiscount * (taxRate / 100);
  const total = afterDiscount + taxAmount;

  const fmt = (n: number) => `${sym}${n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;

  const addItem = useCallback(() => {
    setItems(prev => [...prev, { id: uid(), description: '', quantity: 1, rate: 0 }]);
  }, []);

  const removeItem = useCallback((id: string) => {
    setItems(prev => prev.length > 1 ? prev.filter(i => i.id !== id) : prev);
  }, []);

  const updateItem = useCallback((id: string, field: keyof LineItem, value: string | number) => {
    setItems(prev => prev.map(i => i.id === id ? { ...i, [field]: value } : i));
  }, []);

  const handleDownload = useCallback(async () => {
    if (!from.name.trim()) { setError('Please enter your business name.'); return; }
    if (!to.name.trim() && !to.company.trim()) { setError('Please enter client name or company.'); return; }
    if (items.every(i => !i.description.trim())) { setError('Please add at least one item description.'); return; }

    setLoading(true);
    setError('');

    try {
      const res = await fetch('/api/demos/invoice-forge', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          invoiceNumber, date, dueDate, currency, taxRate, discount, notes,
          from, to,
          items: items.filter(i => i.description.trim()).map(({ description, quantity, rate }) => ({ description, quantity, rate })),
        }),
      });

      if (!res.ok) {
        const data = await res.json().catch(() => ({ error: 'Download failed.' }));
        throw new Error(data.error || 'Download failed.');
      }

      const blob = await res.blob();
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `invoice-${invoiceNumber}.pdf`;
      a.click();
      URL.revokeObjectURL(url);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to generate PDF.');
    } finally {
      setLoading(false);
    }
  }, [from, to, items, invoiceNumber, date, dueDate, currency, taxRate, discount, notes]);

  const inputClass = 'w-full bg-black/30 border border-slate-700 rounded-lg px-3 py-2 text-sm text-white placeholder-gray-600 focus:border-sky-500 focus:outline-none transition-colors';
  const labelClass = 'text-xs text-gray-400 mb-1 block';

  return (
    <main className="min-h-screen bg-[#0C1222]">
      <div className="max-w-5xl mx-auto px-6 py-8">
        {/* Back */}
        <Link href="/demos" className="inline-flex items-center gap-2 text-gray-500 hover:text-gray-300 text-sm mb-8 transition-colors">
          <ArrowLeft className="w-4 h-4" /> Back to Demos
        </Link>

        {/* Header */}
        <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} className="mb-8">
          <div className="flex items-center gap-3 mb-3">
            <div className="w-10 h-10 rounded-xl bg-blue-500/10 border border-blue-500/20 flex items-center justify-center">
              <FileText className="w-5 h-5 text-blue-400" />
            </div>
            <div>
              <h1 className="text-2xl font-bold text-white">InvoiceForge</h1>
              <p className="text-gray-500 text-sm">Professional invoice generator with PDF export</p>
            </div>
          </div>
        </motion.div>

        <div className="grid lg:grid-cols-3 gap-6">
          {/* Left: Form (2 cols) */}
          <div className="lg:col-span-2 space-y-6">
            {/* Invoice Details Row */}
            <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.1 }}>
              <div className="bg-white/[0.02] border border-slate-800/50 rounded-xl p-6">
                <h2 className="text-sm font-semibold text-white mb-4">Invoice Details</h2>
                <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                  <div>
                    <label className={labelClass}>Invoice #</label>
                    <input value={invoiceNumber} onChange={e => setInvoiceNumber(e.target.value)} className={inputClass} />
                  </div>
                  <div>
                    <label className={labelClass}>Date</label>
                    <input type="date" value={date} onChange={e => setDate(e.target.value)} className={inputClass} />
                  </div>
                  <div>
                    <label className={labelClass}>Due Date</label>
                    <input type="date" value={dueDate} onChange={e => setDueDate(e.target.value)} className={inputClass} />
                  </div>
                  <div>
                    <label className={labelClass}>Currency</label>
                    <select value={currency} onChange={e => setCurrency(e.target.value)} className={inputClass}>
                      {CURRENCIES.map(c => <option key={c.code} value={c.code} className="bg-gray-900">{c.label}</option>)}
                    </select>
                  </div>
                </div>
              </div>
            </motion.div>

            {/* From / To */}
            <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.15 }}>
              <div className="grid md:grid-cols-2 gap-6">
                <div className="bg-white/[0.02] border border-slate-800/50 rounded-xl p-6">
                  <h2 className="text-sm font-semibold text-white mb-4">From (Your Business)</h2>
                  <div className="space-y-3">
                    <div><label className={labelClass}>Business Name *</label><input value={from.name} onChange={e => setFrom(p => ({...p, name: e.target.value}))} placeholder="Acme Corp" className={inputClass} /></div>
                    <div><label className={labelClass}>Address</label><textarea value={from.address} onChange={e => setFrom(p => ({...p, address: e.target.value}))} placeholder="123 Main St\nCity, State 12345" rows={2} className={inputClass + ' resize-none'} /></div>
                    <div><label className={labelClass}>Email</label><input type="email" value={from.email} onChange={e => setFrom(p => ({...p, email: e.target.value}))} placeholder="billing@acme.com" className={inputClass} /></div>
                  </div>
                </div>
                <div className="bg-white/[0.02] border border-slate-800/50 rounded-xl p-6">
                  <h2 className="text-sm font-semibold text-white mb-4">Bill To (Client)</h2>
                  <div className="space-y-3">
                    <div><label className={labelClass}>Client Name *</label><input value={to.name} onChange={e => setTo(p => ({...p, name: e.target.value}))} placeholder="Jane Doe" className={inputClass} /></div>
                    <div><label className={labelClass}>Company</label><input value={to.company} onChange={e => setTo(p => ({...p, company: e.target.value}))} placeholder="Client Inc." className={inputClass} /></div>
                    <div><label className={labelClass}>Address</label><textarea value={to.address} onChange={e => setTo(p => ({...p, address: e.target.value}))} placeholder="456 Oak Ave\nCity, State 67890" rows={2} className={inputClass + ' resize-none'} /></div>
                    <div><label className={labelClass}>Email</label><input type="email" value={to.email} onChange={e => setTo(p => ({...p, email: e.target.value}))} placeholder="jane@client.com" className={inputClass} /></div>
                  </div>
                </div>
              </div>
            </motion.div>

            {/* Line Items */}
            <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.2 }}>
              <div className="bg-white/[0.02] border border-slate-800/50 rounded-xl p-6">
                <h2 className="text-sm font-semibold text-white mb-4">Line Items</h2>
                <div className="space-y-3">
                  {/* Header */}
                  <div className="grid grid-cols-12 gap-3 text-xs text-gray-500 px-1 hidden md:grid">
                    <div className="col-span-6">Description</div>
                    <div className="col-span-2 text-right">Qty</div>
                    <div className="col-span-2 text-right">Rate</div>
                    <div className="col-span-1 text-right">Amount</div>
                    <div className="col-span-1" />
                  </div>
                  {items.map((item) => (
                    <div key={item.id} className="grid grid-cols-12 gap-3 items-center">
                      <div className="col-span-12 md:col-span-6">
                        <input
                          value={item.description}
                          onChange={e => updateItem(item.id, 'description', e.target.value)}
                          placeholder="Service or product description"
                          className={inputClass}
                        />
                      </div>
                      <div className="col-span-4 md:col-span-2">
                        <input
                          type="number"
                          min={1}
                          value={item.quantity}
                          onChange={e => updateItem(item.id, 'quantity', Math.max(1, parseInt(e.target.value) || 1))}
                          className={inputClass + ' text-right'}
                        />
                      </div>
                      <div className="col-span-4 md:col-span-2">
                        <input
                          type="number"
                          min={0}
                          step={0.01}
                          value={item.rate}
                          onChange={e => updateItem(item.id, 'rate', Math.max(0, parseFloat(e.target.value) || 0))}
                          className={inputClass + ' text-right'}
                        />
                      </div>
                      <div className="col-span-3 md:col-span-1 text-right text-sm text-gray-400 font-mono">
                        {fmt(item.quantity * item.rate)}
                      </div>
                      <div className="col-span-1">
                        <button
                          onClick={() => removeItem(item.id)}
                          className="p-1.5 rounded-lg hover:bg-red-500/10 text-gray-600 hover:text-red-400 transition-colors"
                          disabled={items.length <= 1}
                        >
                          <Trash2 className="w-4 h-4" />
                        </button>
                      </div>
                    </div>
                  ))}
                </div>
                <button
                  onClick={addItem}
                  className="mt-4 flex items-center gap-2 px-4 py-2 rounded-lg border border-dashed border-slate-700 text-gray-400 text-sm hover:border-sky-500/30 hover:text-sky-400 transition-colors"
                >
                  <Plus className="w-4 h-4" /> Add Line Item
                </button>
              </div>
            </motion.div>

            {/* Tax / Discount / Notes */}
            <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.25 }}>
              <div className="grid md:grid-cols-3 gap-6">
                <div className="bg-white/[0.02] border border-slate-800/50 rounded-xl p-6">
                  <label className={labelClass}>Tax Rate (%)</label>
                  <input type="number" min={0} max={50} step={0.1} value={taxRate} onChange={e => setTaxRate(Math.max(0, parseFloat(e.target.value) || 0))} className={inputClass} />
                </div>
                <div className="bg-white/[0.02] border border-slate-800/50 rounded-xl p-6">
                  <label className={labelClass}>Discount (%)</label>
                  <input type="number" min={0} max={100} step={0.1} value={discount} onChange={e => setDiscount(Math.max(0, parseFloat(e.target.value) || 0))} className={inputClass} />
                </div>
                <div className="bg-white/[0.02] border border-slate-800/50 rounded-xl p-6">
                  <label className={labelClass}>Notes</label>
                  <textarea value={notes} onChange={e => setNotes(e.target.value)} rows={2} className={inputClass + ' resize-none'} />
                </div>
              </div>
            </motion.div>
          </div>

          {/* Right: Summary + Download */}
          <motion.div initial={{ opacity: 0, x: 10 }} animate={{ opacity: 1, x: 0 }} transition={{ delay: 0.3 }}>
            <div className="sticky top-8 space-y-6">
              <div className="bg-white/[0.02] border border-slate-800/50 rounded-xl p-6">
                <h2 className="text-sm font-semibold text-white mb-4 flex items-center gap-2">
                  <DollarSign className="w-4 h-4 text-blue-400" /> Summary
                </h2>
                <div className="space-y-3">
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-400">Subtotal</span>
                    <span className="text-white font-mono">{fmt(subtotal)}</span>
                  </div>
                  {discount > 0 && (
                    <div className="flex justify-between text-sm">
                      <span className="text-gray-400">Discount ({discount}%)</span>
                      <span className="text-emerald-400 font-mono">-{fmt(discountAmount)}</span>
                    </div>
                  )}
                  {taxRate > 0 && (
                    <div className="flex justify-between text-sm">
                      <span className="text-gray-400">Tax ({taxRate}%)</span>
                      <span className="text-white font-mono">{fmt(taxAmount)}</span>
                    </div>
                  )}
                  <div className="border-t border-slate-800/50 pt-3">
                    <div className="flex justify-between">
                      <span className="text-white font-semibold">Total</span>
                      <span className="text-xl font-bold text-white font-mono">{fmt(total)}</span>
                    </div>
                  </div>
                </div>
              </div>

              <button
                onClick={handleDownload}
                disabled={loading}
                className="w-full flex items-center justify-center gap-2 px-6 py-4 rounded-xl bg-gradient-to-r from-blue-500/80 to-sky-500/80 hover:from-blue-500 hover:to-sky-500 text-white font-semibold text-sm disabled:opacity-40 disabled:cursor-not-allowed transition-all"
              >
                {loading ? (
                  <><Loader2 className="w-5 h-5 animate-spin" /> Generating PDF...</>
                ) : (
                  <><Download className="w-5 h-5" /> Download PDF Invoice</>
                )}
              </button>

              {error && <p className="text-red-400 text-sm text-center">{error}</p>}

              <div className="text-xs text-gray-600 text-center">
                Invoice #{invoiceNumber} \u2022 {items.filter(i => i.description.trim()).length} items
              </div>
            </div>
          </motion.div>
        </div>

        {/* Footer */}
        <div className="text-center mt-12 text-gray-700 text-xs">
          Built by The Hearth \u2022 <Link href="/demos" className="text-sky-500/50 hover:text-sky-400">View all demos</Link>
        </div>
      </div>
    </main>
  );
}
