'use client';

import { useEffect, useState } from 'react';
import { motion } from 'framer-motion';
import {
  FileText, Loader2, AlertCircle, AlertTriangle, CalendarClock, Receipt,
} from 'lucide-react';
import { formatEur } from '../lib/conversion-pricing';

interface LineItem {
  projectId: string;
  name: string;
  sourceLanguage: string | null;
  targetLanguage: string | null;
  completedAt: string | null;
  grossCents: number;
  creditCents: number;
  amountCents: number;
}

interface InvoiceData {
  company: {
    id: string;
    name: string;
    package: string;
    suspended: boolean;
    suspensionReason: string | null;
    owner: { email: string; name: string | null } | null;
  };
  period: { start: string; end: string; chargeDate: string };
  credits?: { allowanceCents: number; remainingCents: number; usedCents: number };
  invoice: {
    items: LineItem[];
    slotChargesCents: number;
    grossCents: number;
    creditCents: number;
    conversionCents: number;
    amountCents: number;
  };
  records: Array<{
    id: string;
    periodStart: string;
    periodEnd: string;
    amountCents: number;
    status: string;
    fattureInCloudDocumentId: string | null;
  }>;
}

const eur = (cents: number) => formatEur(cents / 100);

const fmtDate = (iso: string | null) =>
  iso ? new Date(iso).toLocaleDateString('it-IT', { day: '2-digit', month: 'short', year: 'numeric' }) : '—';

const fmtMonth = (iso: string) =>
  new Date(iso).toLocaleDateString('it-IT', { month: 'long', year: 'numeric' });

const lang = (s: string | null) => (s ?? '').toUpperCase();

const STATUS_STYLE: Record<string, string> = {
  charged: 'text-green-400 bg-green-500/10',
  failed: 'text-red-400 bg-red-500/10',
  skipped: 'text-muted bg-surface',
  pending: 'text-amber-400 bg-amber-500/10',
};

export default function CompanyInvoice() {
  const [data, setData] = useState<InvoiceData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    fetch('/api/billing/invoice', { credentials: 'include' })
      .then(async (res) => {
        if (!res.ok) {
          const d = await res.json().catch(() => ({}));
          throw new Error(d.error || 'Failed to load invoice');
        }
        return res.json();
      })
      .then(setData)
      .catch((e) => setError(e instanceof Error ? e.message : 'Failed to load invoice'))
      .finally(() => setLoading(false));
  }, []);

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <Loader2 className="w-8 h-8 animate-spin text-accent" />
      </div>
    );
  }

  if (error || !data) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-center">
          <AlertCircle className="w-12 h-12 text-red-400 mx-auto mb-3" />
          <p className="text-red-400">{error ?? 'No invoice data available'}</p>
        </div>
      </div>
    );
  }

  const { invoice, period, company, records } = data;

  return (
    <div className="space-y-6">
      {/* Header */}
      <motion.div initial={{ opacity: 0, y: -10 }} animate={{ opacity: 1, y: 0 }}
        className="flex items-center justify-between gap-4">
        <div>
          <h2 className="text-2xl font-bold text-foreground flex items-center gap-2">
            <Receipt className="w-6 h-6 text-accent-light" /> Monthly Invoice
          </h2>
          <p className="text-sm text-muted mt-1">
            {company.name} · {fmtMonth(period.start)}
          </p>
        </div>
        <div className="text-right">
          <p className="text-[10px] text-muted uppercase tracking-wider font-medium">Estimated total</p>
          <p className="text-3xl font-bold text-foreground tabular-nums">{eur(invoice.amountCents)}</p>
        </div>
      </motion.div>

      {company.suspended && (
        <div className="flex items-start gap-3 bg-red-500/8 border border-red-500/20 rounded-xl px-4 py-3">
          <AlertTriangle className="w-5 h-5 text-red-400 shrink-0 mt-0.5" />
          <div>
            <p className="text-sm font-semibold text-red-400">Account suspended</p>
            <p className="text-[12px] text-muted leading-relaxed mt-0.5">
              {company.suspensionReason ?? 'An invoice could not be charged. Settle it to restore access.'}
            </p>
          </div>
        </div>
      )}

      {/* Charge notice */}
      <div className="flex items-center gap-2 bg-accent/5 border border-accent/15 rounded-xl px-4 py-3">
        <CalendarClock className="w-4 h-4 text-accent-light shrink-0" />
        <p className="text-[12px] text-muted">
          This invoice is charged automatically on{' '}
          <span className="text-foreground font-medium">{fmtDate(period.chargeDate)}</span>{' '}
          to the payment method on file. An invoice is issued once the charge succeeds.
        </p>
      </div>

      {/* Line items */}
      <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.1 }}
        className="glass rounded-xl overflow-hidden">
        <div className="px-5 py-4 border-b border-border">
          <h3 className="text-sm font-semibold text-foreground flex items-center gap-2">
            <FileText className="w-4 h-4 text-accent-light" /> Conversions this period
          </h3>
        </div>

        {invoice.items.length === 0 ? (
          <div className="py-12 text-center text-sm text-muted">
            No conversions completed yet this month.
          </div>
        ) : (
          <div>
            <div className="grid grid-cols-[1fr_120px_100px_110px_110px_110px] gap-3 px-5 py-2.5 bg-surface text-[10px] text-muted uppercase tracking-wider font-semibold border-b border-border">
              <span>Conversion</span>
              <span>Pair</span>
              <span className="text-center">Completed</span>
              <span className="text-right">List price</span>
              <span className="text-right">Credit</span>
              <span className="text-right">Billed</span>
            </div>
            {invoice.items.map((it, i) => (
              <div key={it.projectId}
                className={`grid grid-cols-[1fr_120px_100px_110px_110px_110px] gap-3 px-5 py-3 items-center text-xs border-t border-border/50 ${i % 2 !== 0 ? 'bg-surface/30' : ''}`}>
                <p className="font-medium text-foreground truncate">{it.name}</p>
                <span className="text-muted">{lang(it.sourceLanguage)} → {lang(it.targetLanguage)}</span>
                <span className="text-center text-muted tabular-nums">{fmtDate(it.completedAt)}</span>
                <span className="text-right text-muted tabular-nums">{eur(it.grossCents)}</span>
                <span className="text-right text-sky-400 tabular-nums">{it.creditCents > 0 ? `−${eur(it.creditCents)}` : '—'}</span>
                <span className="text-right font-medium text-foreground tabular-nums">{eur(it.amountCents)}</span>
              </div>
            ))}

            {/* Totals */}
            <div className="border-t border-border bg-surface/40 px-5 py-3 space-y-1.5">
              <div className="flex items-center justify-between text-xs">
                <span className="text-muted">Conversions list price</span>
                <span className="tabular-nums text-foreground">{eur(invoice.grossCents)}</span>
              </div>
              {invoice.creditCents > 0 && (
                <div className="flex items-center justify-between text-xs">
                  <span className="text-sky-400">License credit applied</span>
                  <span className="tabular-nums text-sky-400">−{eur(invoice.creditCents)}</span>
                </div>
              )}
              {invoice.slotChargesCents > 0 && (
                <div className="flex items-center justify-between text-xs">
                  <span className="text-muted">Extra conversion slots</span>
                  <span className="tabular-nums text-foreground">{eur(invoice.slotChargesCents)}</span>
                </div>
              )}
              <div className="flex items-center justify-between pt-1.5 border-t border-border/50">
                <span className="text-sm font-bold text-foreground">Total due</span>
                <span className="text-lg font-bold text-foreground tabular-nums">{eur(invoice.amountCents)}</span>
              </div>
              {invoice.amountCents === 0 && invoice.grossCents > 0 && (
                <p className="text-[11px] text-sky-400 pt-1">Fully covered by your annual license credit — nothing to pay this month.</p>
              )}
            </div>
          </div>
        )}
      </motion.div>

      {/* Past invoices */}
      <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.2 }}
        className="glass rounded-xl overflow-hidden">
        <div className="px-5 py-4 border-b border-border">
          <h3 className="text-sm font-semibold text-foreground">Past invoices</h3>
        </div>
        {records.length === 0 ? (
          <div className="py-10 text-center text-sm text-muted">No past invoices yet.</div>
        ) : (
          <div>
            <div className="grid grid-cols-[1fr_120px_120px] gap-3 px-5 py-2.5 bg-surface text-[10px] text-muted uppercase tracking-wider font-semibold border-b border-border">
              <span>Period</span>
              <span className="text-center">Status</span>
              <span className="text-right">Amount</span>
            </div>
            {records.map((r, i) => (
              <div key={r.id}
                className={`grid grid-cols-[1fr_120px_120px] gap-3 px-5 py-3 items-center text-xs border-t border-border/50 ${i % 2 !== 0 ? 'bg-surface/30' : ''}`}>
                <span className="text-foreground capitalize">{fmtMonth(r.periodStart)}</span>
                <span className="text-center">
                  <span className={`px-2 py-0.5 rounded-full text-[10px] font-medium ${STATUS_STYLE[r.status] ?? 'text-muted bg-surface'}`}>
                    {r.status}
                  </span>
                </span>
                <span className="text-right font-medium text-foreground tabular-nums">{eur(r.amountCents)}</span>
              </div>
            ))}
          </div>
        )}
      </motion.div>
    </div>
  );
}
