import { useEffect, useState } from 'react';
import { Clock, Wallet, Receipt, FileText } from 'lucide-react';
import { ResponsiveContainer, BarChart, Bar, XAxis, YAxis, Tooltip, CartesianGrid } from 'recharts';
import { api, qs, fmt } from '../api';
import { Card, KpiCard, Spinner, ErrorBox } from '../components/ui';

const tooltipStyle = {
  contentStyle: { backgroundColor: '#131a2a', border: '1px solid #1f2a44', borderRadius: 8, fontSize: 12 },
  labelStyle: { color: '#8b9bb8' }
};

const THIS_YEAR = new Date().getFullYear();
const YEARS = [THIS_YEAR - 2, THIS_YEAR - 1, THIS_YEAR];

export default function Finance() {
  const [year, setYear] = useState(THIS_YEAR);
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);

  const load = () => {
    setError(null);
    api.get('/finance' + qs({ year })).then(setData).catch(setError);
  };
  useEffect(load, [year]);

  return (
    <div className="space-y-5 fade-in">
      <div className="flex items-center justify-between flex-wrap gap-3">
        <div>
          <h1 className="text-xl font-bold tracking-tight">Financiën</h1>
          <p className="text-[13px] text-muted mt-0.5">Uren en omzet over {data?.year ?? year}</p>
        </div>
        <select
          className="bg-bg-soft border border-border rounded-lg px-3 py-2 text-[13px] focus:outline-none focus:border-accent/60"
          value={year}
          onChange={e => setYear(parseInt(e.target.value))}
        >
          {YEARS.map(y => <option key={y} value={y}>{y}</option>)}
        </select>
      </div>

      {error ? (
        <ErrorBox error={error} onRetry={load} />
      ) : !data ? (
        <Spinner />
      ) : (
        <>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
            <KpiCard icon={Clock} label="Uren dit jaar" value={fmt.hours(data.totals.hoursThisYear)} color="blue" />
            <KpiCard icon={Wallet} label="Betaald dit jaar" value={fmt.euro(data.totals.paidThisYear)} color="green" />
            <KpiCard icon={Receipt} label="Openstaand totaal" value={fmt.euro(data.totals.outstanding)} color="yellow" />
            <KpiCard icon={FileText} label="Concept-facturen" value={fmt.euro(data.totals.draftTotal)} sub="nog niet verzonden" color="accent" />
          </div>

          <div className="grid grid-cols-1 xl:grid-cols-2 gap-4">
            <Card title="Uren per maand" subtitle={`Totaal vs facturabel (${data.year})`}>
              <div className="h-56">
                {data.timeStats.length === 0 ? (
                  <div className="h-full flex items-center justify-center text-muted text-[13px]">Geen uren in {data.year}</div>
                ) : (
                  <ResponsiveContainer width="100%" height="100%">
                    <BarChart data={data.timeStats}>
                      <CartesianGrid strokeDasharray="3 3" stroke="#1f2a44" vertical={false} />
                      <XAxis dataKey="month" tick={{ fill: '#8b9bb8', fontSize: 11 }} axisLine={false} tickLine={false} />
                      <YAxis tick={{ fill: '#8b9bb8', fontSize: 11 }} axisLine={false} tickLine={false} />
                      <Tooltip {...tooltipStyle} cursor={{ fill: 'rgba(0,212,255,0.06)' }} />
                      <Bar dataKey="hours" name="Totaal" fill="#58a6ff" radius={[4, 4, 0, 0]} />
                      <Bar dataKey="billable_hours" name="Facturabel" fill="#00d4ff" radius={[4, 4, 0, 0]} />
                    </BarChart>
                  </ResponsiveContainer>
                )}
              </div>
            </Card>

            <Card title="Omzet per maand" subtitle={`Betaald vs openstaand (${data.year})`}>
              <div className="h-56">
                {data.invoiceStats.length === 0 ? (
                  <div className="h-full flex items-center justify-center text-muted text-[13px]">Geen facturen in {data.year}</div>
                ) : (
                  <ResponsiveContainer width="100%" height="100%">
                    <BarChart data={data.invoiceStats}>
                      <CartesianGrid strokeDasharray="3 3" stroke="#1f2a44" vertical={false} />
                      <XAxis dataKey="month" tick={{ fill: '#8b9bb8', fontSize: 11 }} axisLine={false} tickLine={false} />
                      <YAxis tick={{ fill: '#8b9bb8', fontSize: 11 }} axisLine={false} tickLine={false} tickFormatter={v => `€${v}`} />
                      <Tooltip {...tooltipStyle} formatter={(v) => fmt.euro(v)} cursor={{ fill: 'rgba(0,212,255,0.06)' }} />
                      <Bar dataKey="paid" name="Betaald" fill="#3fb950" radius={[4, 4, 0, 0]} />
                      <Bar dataKey="outstanding" name="Openstaand" fill="#d29922" radius={[4, 4, 0, 0]} />
                    </BarChart>
                  </ResponsiveContainer>
                )}
              </div>
            </Card>
          </div>
        </>
      )}
    </div>
  );
}
