import { useEffect, useState } from 'react';
import { Link, useSearchParams } from 'react-router-dom';
import { SearchX } from 'lucide-react';
import { api, qs, fmt } from '../api';
import { Card, StatusBadge, Badge, Spinner, EmptyState, ErrorBox } from '../components/ui';

const CLIENT_STATUS_LABELS = { lead: 'Lead', active: 'Actief', paused: 'Gepauzeerd', archived: 'Gearchiveerd' };
const TASK_STATUS_LABELS = { todo: 'Te doen', in_progress: 'Bezig', done: 'Klaar', cancelled: 'Geannuleerd' };

function ResultRow({ to, children }) {
  const inner = (
    <div className="flex items-center justify-between gap-2 px-2.5 py-2 rounded-lg hover:bg-card-hover transition-colors">
      {children}
    </div>
  );
  return to ? <Link to={to} className="block">{inner}</Link> : inner;
}

export default function Search() {
  const [params] = useSearchParams();
  const q = (params.get('q') || '').trim();
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    setData(null);
    setError(null);
    if (!q) {
      setData({ clients: [], engagements: [], tasks: [], diagrams: [], notes: [] });
      return;
    }
    api.get(`/search${qs({ q })}`).then(setData).catch(setError);
  }, [q]);

  if (error) return <ErrorBox error={error} onRetry={() => api.get(`/search${qs({ q })}`).then(setData).catch(setError)} />;
  if (!data) return <Spinner text={`Zoeken naar "${q}"...`} />;

  const { clients, engagements, tasks, diagrams, notes } = data;
  const total = clients.length + engagements.length + tasks.length + diagrams.length + notes.length;

  return (
    <div className="space-y-5 fade-in">
      <div>
        <h1 className="text-xl font-bold tracking-tight">Zoekresultaten voor &ldquo;{q}&rdquo;</h1>
        <p className="text-[13px] text-muted mt-0.5">{total} resultaat{total === 1 ? '' : 'en'} gevonden</p>
      </div>

      {total === 0 ? (
        <Card>
          <EmptyState
            icon={SearchX}
            title="Geen resultaten"
            hint={`Er is niets gevonden voor "${q}". Probeer een andere zoekterm.`}
          />
        </Card>
      ) : (
        <div className="grid grid-cols-1 xl:grid-cols-2 gap-4">
          {clients.length > 0 && (
            <Card title="Cliënten" subtitle={`${clients.length} gevonden`}>
              <div className="space-y-1">
                {clients.map(c => (
                  <ResultRow key={c.id} to={`/clients/${c.id}`}>
                    <div className="min-w-0">
                      <div className="text-[13px] font-medium truncate">{c.name}</div>
                      {c.industry && <div className="text-[11px] text-muted">{c.industry}</div>}
                    </div>
                    <StatusBadge status={c.status} labels={CLIENT_STATUS_LABELS} />
                  </ResultRow>
                ))}
              </div>
            </Card>
          )}

          {engagements.length > 0 && (
            <Card title="Engagements" subtitle={`${engagements.length} gevonden`}>
              <div className="space-y-1">
                {engagements.map(e => (
                  <ResultRow key={e.id} to={`/engagements/${e.id}`}>
                    <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={{ planned: 'Gepland', in_progress: 'Lopend', completed: 'Afgerond', on_hold: 'On hold' }} />
                  </ResultRow>
                ))}
              </div>
            </Card>
          )}

          {tasks.length > 0 && (
            <Card title="Taken" subtitle={`${tasks.length} gevonden`}>
              <div className="space-y-1">
                {tasks.map(t => (
                  <ResultRow key={t.id}>
                    <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.engagement_title ? ` · ${t.engagement_title}` : ''}</div>
                    </div>
                    <StatusBadge status={t.status} labels={TASK_STATUS_LABELS} />
                  </ResultRow>
                ))}
              </div>
            </Card>
          )}

          {diagrams.length > 0 && (
            <Card title="Diagrammen" subtitle={`${diagrams.length} gevonden`}>
              <div className="space-y-1">
                {diagrams.map(d => (
                  <ResultRow key={d.id} to="/diagrams">
                    <div className="min-w-0">
                      <div className="text-[13px] font-medium truncate">{d.name}</div>
                      <div className="text-[11px] text-muted">{d.client_name}</div>
                    </div>
                    <Badge color="purple">{d.diagram_type}</Badge>
                  </ResultRow>
                ))}
              </div>
            </Card>
          )}

          {notes.length > 0 && (
            <Card title="Notities" subtitle={`${notes.length} gevonden`}>
              <div className="space-y-1">
                {notes.map(n => (
                  <ResultRow key={n.id} to={`/clients/${n.client_id}`}>
                    <div className="min-w-0">
                      <div className="text-[13px] truncate">
                        {n.content.length > 120 ? `${n.content.slice(0, 120)}…` : n.content}
                      </div>
                      <div className="text-[11px] text-muted">{n.client_name} · {fmt.date(n.created_at)}</div>
                    </div>
                  </ResultRow>
                ))}
              </div>
            </Card>
          )}
        </div>
      )}
    </div>
  );
}
