'use client';

import { useEffect, useState } from 'react';
import { motion } from 'framer-motion';
import {
  Cpu, AlertCircle, Loader2, TrendingDown,
  Coins, ArrowUpRight, Gift, Receipt, CalendarClock, AlertTriangle,
} from 'lucide-react';
import { useSession } from '../lib/session-context';
import { formatEur } from '../lib/conversion-pricing';

/** Display helper: render a cent amount as a € price. */
function eur(cents: number): string {
  return formatEur(cents / 100);
}

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

interface InvoiceItem {
  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: InvoiceItem[];
    slotChargesCents: number;
    grossCents: number;
    creditCents: number;
    conversionCents: number;
    amountCents: number;
  };
}

const TIER_CONFIG = {
  starter: { label: 'Starter', color: 'text-sky-400', bg: 'bg-sky-500/10' },
  professional: { label: 'Professional', color: 'text-purple-400', bg: 'bg-purple-500/10' },
  enterprise: { label: 'Enterprise', color: 'text-amber-400', bg: 'bg-amber-500/10' },
};

export default function CompanyTokens() {
  const { user: sessionUser } = useSession();
  const [data, setData] = useState<InvoiceData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!sessionUser?.companyId) {
      setError('You must belong to a company to view license credits');
      setLoading(false);
      return;
    }
    if (!sessionUser?.isOwner) {
      setError('Only company owners can view license credits');
      setLoading(false);
      return;
    }
    // Single source of truth shared with the Invoices page.
    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 license credits');
        }
        return res.json();
      })
      .then(setData)
      .catch((err) => setError(err instanceof Error ? err.message : 'Failed to load license credits'))
      .finally(() => setLoading(false));
  }, [sessionUser?.companyId, sessionUser?.isOwner]);

  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 data available'}</p>
        </div>
      </div>
    );
  }

  const tierConfig = TIER_CONFIG[data.company.package as keyof typeof TIER_CONFIG] || TIER_CONFIG.starter;
  // All figures come straight from the invoice endpoint (same as the Invoices page).
  const allowance = data.credits.allowanceCents;
  const creditUsed = data.credits.usedCents;
  const creditRemaining = data.credits.remainingCents;
  const billableThisMonth = data.invoice.amountCents;
  const usagePercent = allowance > 0 ? Math.round((creditUsed / allowance) * 100) : 0;

  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">
        <div>
          <h2 className="text-2xl font-bold text-foreground flex items-center gap-2">
            <Cpu className="w-6 h-6 text-accent-light" /> License Credits
          </h2>
          <p className="text-sm text-muted mt-1">
            Annual license credit included with your plan, consumed across all conversions
          </p>
        </div>
        <div className={`px-3 py-1.5 rounded-full text-xs font-semibold ${tierConfig.color} ${tierConfig.bg}`}>
          {data.company.name}
        </div>
      </motion.div>

      {data.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">
              {data.company.suspensionReason ?? 'An invoice could not be charged. Settle it to restore access.'}
            </p>
          </div>
        </div>
      )}

      {/* Credit Stats */}
      <div className="grid grid-cols-4 gap-4">
        <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.1 }}
          className="glass rounded-xl p-5 border border-sky-500/20">
          <div className="flex items-center gap-2 mb-3">
            <div className="w-8 h-8 rounded-lg bg-sky-500/15 flex items-center justify-center">
              <Gift className="w-4 h-4 text-sky-400" />
            </div>
            <p className="text-[10px] text-sky-400 uppercase tracking-wider font-medium">Plan Credit</p>
          </div>
          <p className="text-3xl font-bold text-sky-400">{eur(allowance)}</p>
          <p className="text-xs text-muted mt-1">Included with your annual license · renews yearly</p>
        </motion.div>

        <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.15 }}
          className="glass rounded-xl p-5">
          <div className="flex items-center gap-2 mb-3">
            <div className="w-8 h-8 rounded-lg bg-sky-500/10 flex items-center justify-center">
              <Coins className="w-4 h-4 text-sky-400" />
            </div>
            <p className="text-[10px] text-muted uppercase tracking-wider font-medium">Credit Used</p>
          </div>
          <p className="text-3xl font-bold text-foreground">{eur(creditUsed)}</p>
          <p className="text-xs text-sky-400 mt-1">applied to your conversions</p>
        </motion.div>

        <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.2 }}
          className="glass rounded-xl p-5">
          <div className="flex items-center gap-2 mb-3">
            <div className="w-8 h-8 rounded-lg bg-red-500/10 flex items-center justify-center">
              <TrendingDown className="w-4 h-4 text-red-400" />
            </div>
            <p className="text-[10px] text-muted uppercase tracking-wider font-medium">Billable this month</p>
          </div>
          <p className="text-3xl font-bold text-foreground">{eur(billableThisMonth)}</p>
          <p className="text-xs text-red-400 mt-1">charged on the 1st · see Invoices</p>
        </motion.div>

        <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.25 }}
          className="glass rounded-xl p-5">
          <div className="flex items-center gap-2 mb-3">
            <div className="w-8 h-8 rounded-lg bg-green-500/10 flex items-center justify-center">
              <ArrowUpRight className="w-4 h-4 text-green-400" />
            </div>
            <p className="text-[10px] text-muted uppercase tracking-wider font-medium">Credit Remaining</p>
          </div>
          <p className={`text-3xl font-bold ${creditRemaining < allowance * 0.1 ? 'text-amber-400' : 'text-foreground'}`}>
            {eur(creditRemaining)}
          </p>
          <p className="text-xs text-muted mt-1">
            {creditRemaining < allowance * 0.1 ? 'Low — conversions billed at full rate' : 'Available this license year'}
          </p>
        </motion.div>
      </div>

      {/* Annual credit usage bar */}
      <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.35 }}
        className="glass rounded-xl p-5">
        <div className="flex items-center justify-between mb-3">
          <p className="text-sm font-semibold text-foreground">Annual credit usage</p>
          <p className={`text-sm font-medium ${usagePercent > 90 ? 'text-amber-400' : 'text-muted'}`}>
            {usagePercent}% of plan credit used
          </p>
        </div>
        <div className="h-3 bg-surface-light rounded-full overflow-hidden">
          <motion.div
            initial={{ width: 0 }}
            animate={{ width: `${Math.min(100, usagePercent)}%` }}
            transition={{ duration: 0.8, delay: 0.4 }}
            className="h-full bg-sky-400 rounded-full"
          />
        </div>
        <div className="flex items-center gap-4 mt-2">
          <div className="flex items-center gap-1.5 text-xs">
            <span className="w-2.5 h-2.5 rounded-full bg-sky-400 inline-block" />
            <span className="text-sky-400">{eur(creditUsed)} used</span>
          </div>
          <span className="text-xs text-muted ml-auto">{eur(creditRemaining)} of {eur(allowance)} remaining this license year</span>
        </div>
      </motion.div>

      {/* This month's conversions — identical line items to the Invoices page */}
      <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.5 }}
        className="glass rounded-xl overflow-hidden">
        <div className="px-5 py-4 border-b border-border flex items-center justify-between">
          <h3 className="text-sm font-semibold text-foreground flex items-center gap-2">
            <Receipt className="w-4 h-4 text-accent-light" /> Conversions this month
          </h3>
          <div className="flex items-center gap-1.5 text-[11px] text-muted">
            <CalendarClock className="w-3.5 h-3.5" /> Charged {fmtDate(data.period.chargeDate)}
          </div>
        </div>

        {data.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>
            {data.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>
            ))}
            <div className="border-t border-border bg-surface/60 px-5 py-3 space-y-1.5">
              <div className="flex items-center justify-between text-xs">
                <span className="text-muted">List price</span>
                <span className="tabular-nums text-foreground">{eur(data.invoice.grossCents)}</span>
              </div>
              {data.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(data.invoice.creditCents)}</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">Billable this month</span>
                <span className="text-foreground font-bold tabular-nums">{eur(billableThisMonth)}</span>
              </div>
            </div>
          </div>
        )}
      </motion.div>
    </div>
  );
}
