import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { Plus, FolderKanban } from 'lucide-react';
import { api, fmt } from '../api';
import { Card, StatusBadge, Btn, Field, inputCls, Modal, Spinner, EmptyState, ErrorBox } from '../components/ui';

export const PROJECT_STATUS_LABELS = {
  planning: 'Planning', in_progress: 'Bezig', completed: 'Afgerond', on_hold: 'On hold'
};
export const PRIORITY_LABELS = {
  low: 'Laag', medium: 'Gemiddeld', high: 'Hoog', critical: 'Kritiek'
};

const EMPTY_FORM = {
  name: '', client_id: '', description: '', status: 'planning',
  priority: 'medium', budget: '', start_date: '', end_date: ''
};

// Gedeeld formulier — ook gebruikt door ProjectDetail (bewerken)
export function ProjectModal({ open, onClose, clients, project, onSaved }) {
  const [form, setForm] = useState(EMPTY_FORM);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    if (!open) return;
    setError(null);
    if (project) {
      setForm({
        name: project.name || '',
        client_id: project.client_id || '',
        description: project.description || '',
        status: project.status || 'planning',
        priority: project.priority || 'medium',
        budget: project.budget ?? '',
        start_date: project.start_date || '',
        end_date: project.end_date || ''
      });
    } else {
      setForm(EMPTY_FORM);
    }
  }, [open, project]);

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const save = async () => {
    if (!form.name.trim()) return setError('Projectnaam is verplicht');
    setSaving(true);
    setError(null);
    try {
      const body = {
        ...form,
        client_id: form.client_id || null,
        budget: form.budget === '' ? null : Number(form.budget),
        start_date: form.start_date || null,
        end_date: form.end_date || null
      };
      if (project) await api.put(`/projects/${project.id}`, body);
      else await api.post('/projects', body);
      onClose();
      onSaved?.();
    } catch (e) {
      setError(e.message);
    } finally {
      setSaving(false);
    }
  };

  return (
    <Modal open={open} onClose={onClose} title={project ? 'Project bewerken' : 'Nieuw project'}>
      <div className="space-y-3">
        <Field label="Naam *">
          <input className={inputCls} value={form.name} onChange={e => set('name', e.target.value)} placeholder="Bijv. migratie naar Azure" />
        </Field>
        <Field label="Cliënt">
          <select className={inputCls} value={form.client_id} onChange={e => set('client_id', e.target.value)}>
            <option value="">— Geen —</option>
            {clients.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
          </select>
        </Field>
        <Field label="Beschrijving">
          <textarea className={inputCls} rows={3} value={form.description} onChange={e => set('description', e.target.value)} />
        </Field>
        <div className="grid grid-cols-2 gap-3">
          <Field label="Status">
            <select className={inputCls} value={form.status} onChange={e => set('status', e.target.value)}>
              {Object.entries(PROJECT_STATUS_LABELS).map(([k, l]) => <option key={k} value={k}>{l}</option>)}
            </select>
          </Field>
          <Field label="Prioriteit">
            <select className={inputCls} value={form.priority} onChange={e => set('priority', e.target.value)}>
              {Object.entries(PRIORITY_LABELS).map(([k, l]) => <option key={k} value={k}>{l}</option>)}
            </select>
          </Field>
        </div>
        <div className="grid grid-cols-3 gap-3">
          <Field label="Budget (€)">
            <input type="number" min="0" step="0.01" className={inputCls} value={form.budget} onChange={e => set('budget', e.target.value)} />
          </Field>
          <Field label="Startdatum">
            <input type="date" className={inputCls} value={form.start_date} onChange={e => set('start_date', e.target.value)} />
          </Field>
          <Field label="Einddatum">
            <input type="date" className={inputCls} value={form.end_date} onChange={e => set('end_date', e.target.value)} />
          </Field>
        </div>
      </div>
      {error && <div className="text-red text-[12px] mt-3">{error}</div>}
      <div className="flex justify-end gap-2 mt-4">
        <Btn variant="secondary" onClick={onClose}>Annuleren</Btn>
        <Btn onClick={save} loading={saving}>{project ? 'Opslaan' : 'Aanmaken'}</Btn>
      </div>
    </Modal>
  );
}

export default function Projects() {
  const [projects, setProjects] = useState(null);
  const [clients, setClients] = useState([]);
  const [error, setError] = useState(null);
  const [modalOpen, setModalOpen] = useState(false);

  const load = () => {
    setError(null);
    api.get('/projects').then(setProjects).catch(setError);
  };
  useEffect(load, []);
  useEffect(() => { api.get('/clients').then(setClients).catch(() => {}); }, []);

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

  return (
    <div className="space-y-5 fade-in">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-xl font-bold tracking-tight">Projecten</h1>
          <p className="text-[13px] text-muted mt-0.5">{projects.length} project{projects.length === 1 ? '' : 'en'}</p>
        </div>
        <Btn onClick={() => setModalOpen(true)}><Plus className="w-4 h-4" /> Nieuw project</Btn>
      </div>

      {projects.length === 0 ? (
        <Card>
          <EmptyState
            icon={FolderKanban}
            title="Nog geen projecten"
            hint="Maak je eerste project aan om taken en milestones te beheren."
            action={<Btn onClick={() => setModalOpen(true)}><Plus className="w-4 h-4" /> Nieuw project</Btn>}
          />
        </Card>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
          {projects.map(p => {
            const pct = p.task_count > 0 ? Math.round((p.done_count / p.task_count) * 100) : 0;
            return (
              <Card key={p.id} className="card-hover">
                <div className="flex items-start justify-between gap-2">
                  <div className="min-w-0">
                    <Link to={`/projects/${p.id}`} className="font-semibold text-[14px] hover:text-accent transition-colors block truncate">
                      {p.name}
                    </Link>
                    <div className="text-[12px] text-muted mt-0.5">{p.client_name || 'Geen cliënt'}</div>
                  </div>
                  <StatusBadge status={p.status} labels={PROJECT_STATUS_LABELS} />
                </div>

                <div className="mt-4">
                  <div className="flex items-center justify-between text-[11px] text-muted mb-1">
                    <span>Voortgang</span>
                    <span>{p.done_count}/{p.task_count} taken · {pct}%</span>
                  </div>
                  <div className="h-1.5 rounded-full bg-bg-soft overflow-hidden">
                    <div className="h-full bg-accent rounded-full transition-all" style={{ width: `${pct}%` }} />
                  </div>
                </div>

                <div className="flex items-center justify-between mt-4 text-[12px] text-muted">
                  <span>{fmt.date(p.start_date)} — {fmt.date(p.end_date)}</span>
                  {p.budget != null && <span className="font-medium text-text">{fmt.euro(p.budget)}</span>}
                </div>
              </Card>
            );
          })}
        </div>
      )}

      <ProjectModal
        open={modalOpen}
        onClose={() => setModalOpen(false)}
        clients={clients}
        onSaved={load}
      />
    </div>
  );
}
