import { useEffect, useState } from 'react';
import { Link, useNavigate, useParams } from 'react-router-dom';
import { ArrowLeft, Mail, Trash2 } from 'lucide-react';
import { api, fmt } from '../api';
import { Card, Btn, Spinner, ErrorBox, StatusBadge } from '../components/ui';

const STATUS_LABELS = {
  draft: 'Concept', sent: 'Verzonden', paid: 'Betaald', overdue: 'Verlopen', cancelled: 'Geannuleerd'
};

export default function InvoiceDetail() {
  const { id } = useParams();
  const navigate = useNavigate();
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);
  const [banner, setBanner] = useState(null);
  const [sending, setSending] = useState(false);
  const [statusSaving, setStatusSaving] = useState(false);

  const load = () => {
    setError(null);
    api.get(`/invoices/${id}`).then(setData).catch(setError);
  };
  useEffect(load, [id]);

  const changeStatus = async (status) => {
    setStatusSaving(true);
    setBanner(null);
    try {
      await api.post(`/invoices/${id}/status`, { status });
      load();
    } catch (err) {
      setBanner({ type: 'error', msg: err.message });
    } finally {
      setStatusSaving(false);
    }
  };

  const sendEmail = async () => {
    if (!window.confirm('Factuur per e-mail versturen naar de cliënt?')) return;
    setSending(true);
    setBanner(null);
    try {
      await api.post(`/invoices/${id}/send-email`);
      setBanner({ type: 'success', msg: 'Factuur is succesvol per e-mail verstuurd.' });
      load();
    } catch (err) {
      setBanner({ type: 'error', msg: err.message });
    } finally {
      setSending(false);
    }
  };

  const remove = async () => {
    if (!window.confirm(`Factuur ${data.invoice.number} definitief verwijderen?`)) return;
    try {
      await api.del(`/invoices/${id}`);
      navigate('/invoices');
    } catch (err) {
      setBanner({ type: 'error', msg: err.message });
    }
  };

  if (error) return <ErrorBox error={error} onRetry={load} />;
  if (!data) return <Spinner />;

  const { invoice, items } = data;

  return (
    <div className="space-y-5 fade-in">
      <div className="flex items-center justify-between flex-wrap gap-3">
        <div className="flex items-center gap-3">
          <Link to="/invoices">
            <Btn variant="secondary" size="sm"><ArrowLeft className="w-3.5 h-3.5" /> Terug</Btn>
          </Link>
          <h1 className="text-xl font-bold tracking-tight">{invoice.number}</h1>
          <StatusBadge status={invoice.status} labels={STATUS_LABELS} />
        </div>
        <div className="flex items-center gap-2 flex-wrap">
          <select
            className="bg-bg-soft border border-border rounded-lg px-3 py-2 text-[13px] focus:outline-none focus:border-accent/60 disabled:opacity-50"
            value={invoice.status}
            disabled={statusSaving}
            onChange={e => changeStatus(e.target.value)}
          >
            {Object.entries(STATUS_LABELS).map(([value, label]) => (
              <option key={value} value={value}>{label}</option>
            ))}
          </select>
          <Btn variant="secondary" onClick={sendEmail} loading={sending}>
            <Mail className="w-3.5 h-3.5" /> E-mail versturen
          </Btn>
          <Btn variant="danger" onClick={remove}>
            <Trash2 className="w-3.5 h-3.5" /> Verwijderen
          </Btn>
        </div>
      </div>

      {banner && (
        <div className={`rounded-lg px-4 py-3 text-[13px] border ${
          banner.type === 'success'
            ? 'bg-green/10 border-green/30 text-green'
            : 'bg-red/10 border-red/30 text-red'
        }`}>
          {banner.msg}
        </div>
      )}

      <Card padding={false} className="max-w-3xl">
        <div className="p-6 space-y-6">
          {/* Factuurkop */}
          <div className="flex items-start justify-between gap-4 flex-wrap">
            <div>
              <div className="text-[11px] uppercase tracking-wide text-muted mb-1">Factuur voor</div>
              <div className="text-[15px] font-semibold">{invoice.client_name}</div>
              <div className="text-[12px] text-muted mt-1 space-y-0.5">
                {invoice.contact_name && <div>{invoice.contact_name}</div>}
                {invoice.contact_email && <div>{invoice.contact_email}</div>}
                {invoice.website && <div>{invoice.website}</div>}
              </div>
            </div>
            <div className="text-right text-[13px] space-y-1">
              <div>
                <span className="text-muted">Factuurnummer: </span>
                <span className="font-medium">{invoice.number}</span>
              </div>
              <div>
                <span className="text-muted">Factuurdatum: </span>
                <span>{fmt.date(invoice.date)}</span>
              </div>
              <div>
                <span className="text-muted">Vervaldatum: </span>
                <span>{invoice.due_date ? fmt.date(invoice.due_date) : '-'}</span>
              </div>
            </div>
          </div>

          {/* Items */}
          <div className="overflow-x-auto">
            <table className="w-full text-[13px]">
              <thead>
                <tr className="text-left text-muted border-b border-border-soft">
                  <th className="pb-2 pr-4 font-medium text-[12px]">Omschrijving</th>
                  <th className="pb-2 pr-4 font-medium text-[12px] text-right">Aantal</th>
                  <th className="pb-2 pr-4 font-medium text-[12px] text-right">Tarief</th>
                  <th className="pb-2 font-medium text-[12px] text-right">Totaal</th>
                </tr>
              </thead>
              <tbody>
                {items.map(item => (
                  <tr key={item.id} className="border-b border-border-soft/50">
                    <td className="py-2.5 pr-4">{item.description}</td>
                    <td className="py-2.5 pr-4 text-right text-muted">{(item.quantity || 0).toLocaleString('nl-NL')}</td>
                    <td className="py-2.5 pr-4 text-right text-muted">{fmt.euro(item.unit_price)}</td>
                    <td className="py-2.5 text-right">{fmt.euro(item.total)}</td>
                  </tr>
                ))}
                {items.length === 0 && (
                  <tr><td colSpan={4} className="py-6 text-center text-muted">Geen factuurregels</td></tr>
                )}
              </tbody>
            </table>
          </div>

          {/* Totalen */}
          <div className="flex justify-end">
            <div className="w-64 space-y-1.5 text-[13px]">
              <div className="flex justify-between">
                <span className="text-muted">Subtotaal</span>
                <span>{fmt.euro(invoice.subtotal)}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-muted">BTW</span>
                <span>{fmt.euro(invoice.tax)}</span>
              </div>
              <div className="flex justify-between font-bold text-[15px] border-t border-border-soft pt-1.5">
                <span>Totaal</span>
                <span>{fmt.euro(invoice.total)}</span>
              </div>
            </div>
          </div>

          {invoice.notes && (
            <div className="border-t border-border-soft pt-4">
              <div className="text-[11px] uppercase tracking-wide text-muted mb-1">Notities</div>
              <div className="text-[13px] whitespace-pre-wrap">{invoice.notes}</div>
            </div>
          )}
        </div>
      </Card>
    </div>
  );
}
