import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import {
  Users, Briefcase, CheckCircle2, Clock, Receipt, Wallet,
  AlertTriangle, Lightbulb, Activity, ArrowRight
} from 'lucide-react';
import {
  ResponsiveContainer, BarChart, Bar, XAxis, YAxis, Tooltip, CartesianGrid,
  PieChart, Pie, Cell, Legend
} from 'recharts';
import { api, fmt } from '../api';
import { Card, KpiCard, Badge, StatusBadge, Spinner, ErrorBox, Table } from '../components/ui';

const PIE_COLORS = ['#00d4ff', '#3fb950', '#d29922', '#bc8cff', '#f778ba', '#58a6ff'];

const TYPE_LABELS = {
  assessment: 'Assessment', architecture: 'Architectuur', implementation: 'Implementatie',
  monitoring: 'Monitoring', consulting: 'Consulting', training: 'Training'
};
const STATUS_LABELS = {
  planned: 'Gepland', in_progress: 'Lopend', completed: 'Afgerond', on_hold: 'On hold',
  draft: 'Concept', sent: 'Verzonden', paid: 'Betaald', overdue: 'Verlopen', cancelled: 'Geannuleerd',
  todo: 'Te doen', done: 'Klaar', lead: 'Lead', active: 'Actief', paused: 'Gepauzeerd', archived: 'Gearchiveerd'
};

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

export default function Dashboard() {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);

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

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

  const { stats } = data;
  const hoursChart = data.hoursByMonth.map(m => ({ ...m, maand: m.month.slice(5) }));
  const revenueChart = data.revenueByMonth.map(m => ({ ...m, maand: m.month.slice(5) }));
  const engTypeChart = data.engagementByType.map(e => ({ name: TYPE_LABELS[e.type] || e.type, value: e.cnt }));

  return (
    <div className="space-y-5 fade-in">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-xl font-bold tracking-tight">Dashboard</h1>
          <p className="text-[13px] text-muted mt-0.5">Overzicht van je consultancy-praktijk</p>
        </div>
        <Link to="/clients">
          <span className="text-[13px] text-accent hover:underline flex items-center gap-1">
            Alle cliënten <ArrowRight className="w-3.5 h-3.5" />
          </span>
        </Link>
      </div>

      {/* KPI's */}
      <div className="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-6 gap-3">
        <KpiCard icon={Users} label="Cliënten" value={stats.totalClients} sub={`${stats.activeClients} actief · ${stats.leads} leads`} color="accent" />
        <KpiCard icon={Briefcase} label="Lopende engagements" value={stats.activeEngagements} color="blue" />
        <KpiCard icon={CheckCircle2} label="Open taken" value={stats.totalTasks - stats.completedTasks} sub={stats.overdueTasks > 0 ? `${stats.overdueTasks} te laat` : undefined} color={stats.overdueTasks > 0 ? 'red' : 'green'} />
        <KpiCard icon={Clock} label="Uren totaal" value={fmt.hours(stats.totalHours)} sub={`${fmt.hours(stats.billableHours)} facturabel`} color="purple" />
        <KpiCard icon={Receipt} label="Openstaand" value={fmt.euro(stats.totalOutstanding)} color="yellow" />
        <KpiCard icon={Wallet} label="Betaald" value={fmt.euro(stats.totalPaid)} color="green" />
      </div>

      {/* Grafieken */}
      <div className="grid grid-cols-1 xl:grid-cols-3 gap-4">
        <Card title="Uren per maand" subtitle="Totaal vs facturabel (6 mnd)" className="xl:col-span-2">
          <div className="h-56">
            <ResponsiveContainer width="100%" height="100%">
              <BarChart data={hoursChart}>
                <CartesianGrid strokeDasharray="3 3" stroke="#1f2a44" vertical={false} />
                <XAxis dataKey="maand" 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" name="Facturabel" fill="#00d4ff" radius={[4, 4, 0, 0]} />
              </BarChart>
            </ResponsiveContainer>
          </div>
        </Card>

        <Card title="Engagements per type">
          <div className="h-56">
            {engTypeChart.length === 0 ? (
              <div className="h-full flex items-center justify-center text-muted text-[13px]">Nog geen engagements</div>
            ) : (
              <ResponsiveContainer width="100%" height="100%">
                <PieChart>
                  <Pie data={engTypeChart} dataKey="value" nameKey="name" innerRadius={50} outerRadius={75} paddingAngle={3}>
                    {engTypeChart.map((_, i) => <Cell key={i} fill={PIE_COLORS[i % PIE_COLORS.length]} />)}
                  </Pie>
                  <Tooltip {...tooltipStyle} />
                  <Legend iconSize={8} wrapperStyle={{ fontSize: 11, color: '#8b9bb8' }} />
                </PieChart>
              </ResponsiveContainer>
            )}
          </div>
        </Card>
      </div>

      <div className="grid grid-cols-1 xl:grid-cols-3 gap-4">
        {/* Lopende engagements */}
        <Card
          title="Recente engagements"
          actions={<Link to="/engagements" className="text-[12px] text-accent hover:underline">Alles</Link>}
          className="xl:col-span-1"
        >
          {data.recentEngagements.length === 0 ? (
            <div className="text-muted text-[13px] py-4 text-center">Nog geen engagements</div>
          ) : (
            <div className="space-y-2">
              {data.recentEngagements.slice(0, 6).map(e => (
                <Link key={e.id} to={`/engagements/${e.id}`} className="flex items-center justify-between gap-2 px-2.5 py-2 rounded-lg hover:bg-card-hover transition-colors">
                  <div className="min-w-0">
                    <div className="text-[13px] font-medium truncate">{e.title}</div>
                    <div className="text-[11px] text-muted">{e.client_name}</div>
                  </div>
                  <StatusBadge status={e.status} labels={STATUS_LABELS} />
                </Link>
              ))}
            </div>
          )}
        </Card>

        {/* Aankomende taken */}
        <Card
          title="Taken op de plank"
          actions={<Link to="/tasks" className="text-[12px] text-accent hover:underline">Alles</Link>}
          className="xl:col-span-1"
        >
          {data.upcomingTasks.length === 0 ? (
            <div className="text-muted text-[13px] py-4 text-center">Geen open taken</div>
          ) : (
            <div className="space-y-2">
              {data.upcomingTasks.slice(0, 6).map(t => (
                <div key={t.id} className="flex items-center justify-between gap-2 px-2.5 py-2 rounded-lg hover:bg-card-hover transition-colors">
                  <div className="min-w-0">
                    <div className="text-[13px] font-medium truncate">{t.title}</div>
                    <div className="text-[11px] text-muted">{t.client_name} · {t.due_date ? fmt.date(t.due_date) : 'geen deadline'}</div>
                  </div>
                  <Badge color={STATUS_LABELS && t.priority === 'critical' ? 'red' : t.priority === 'high' ? 'yellow' : 'blue'}>{t.priority}</Badge>
                </div>
              ))}
            </div>
          )}
        </Card>

        {/* Advies + activiteit */}
        <Card title="Slim advies" subtitle="Automatisch gegenereerd" className="xl:col-span-1">
          {data.activeAdvice.length === 0 ? (
            <div className="text-muted text-[13px] py-4 text-center flex flex-col items-center gap-2">
              <Lightbulb className="w-5 h-5" /> Alles onder controle
            </div>
          ) : (
            <div className="space-y-2">
              {data.activeAdvice.slice(0, 5).map(a => (
                <div key={a.id} className="flex items-start gap-2.5 px-2.5 py-2 rounded-lg hover:bg-card-hover">
                  <AlertTriangle className={`w-4 h-4 mt-0.5 shrink-0 ${a.priority === 'critical' ? 'text-red' : a.priority === 'high' ? 'text-yellow' : 'text-blue'}`} />
                  <div className="min-w-0">
                    <div className="text-[12px]">{a.advice_text}</div>
                    <div className="text-[11px] text-muted mt-0.5">{a.client_name}</div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </Card>
      </div>

      {/* Facturen + activiteit */}
      <div className="grid grid-cols-1 xl:grid-cols-2 gap-4">
        <Card title="Omzet per maand" subtitle="Betaald vs openstaand (6 mnd)">
          <div className="h-52">
            <ResponsiveContainer width="100%" height="100%">
              <BarChart data={revenueChart}>
                <CartesianGrid strokeDasharray="3 3" stroke="#1f2a44" vertical={false} />
                <XAxis dataKey="maand" 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>

        <Card
          title="Recente activiteit"
          actions={<Link to="/settings?tab=audit" className="text-[12px] text-accent hover:underline flex items-center gap-1"><Activity className="w-3.5 h-3.5" /> Audit-log</Link>}
          padding={false}
        >
          <div className="p-4">
            <Table
              columns={[
                { label: 'Wie', key: 'username' },
                { label: 'Actie', key: 'action' },
                { label: 'Wanneer', render: r => <span className="text-muted">{fmt.datetime(r.created_at)}</span> }
              ]}
              rows={data.recentAudit}
              keyFn={r => r.id}
              empty={<div className="text-muted text-[13px] py-4 text-center">Nog geen activiteit</div>}
            />
          </div>
        </Card>
      </div>
    </div>
  );
}
