import { useEffect, useState } from 'react';
import { Link, useNavigate, useParams } from 'react-router-dom';
import { ArrowLeft, ChevronLeft, ChevronRight, Pencil, Plus, Trash2, Flag } from 'lucide-react';
import { api, fmt } from '../api';
import { Card, Badge, StatusBadge, Btn, Field, inputCls, Modal, Spinner, ErrorBox, STATUS_COLORS } from '../components/ui';
import { ProjectModal, PROJECT_STATUS_LABELS, PRIORITY_LABELS } from './Projects';

const COLUMNS = [
  { key: 'todo', label: 'Te doen' },
  { key: 'in_progress', label: 'Bezig' },
  { key: 'done', label: 'Klaar' }
];
const STATUS_ORDER = ['todo', 'in_progress', 'done'];
const MILESTONE_LABELS = { pending: 'Open', done: 'Behaald', completed: 'Behaald', missed: 'Gemist' };

const EMPTY_TASK = { title: '', description: '', assignee_id: '', priority: 'medium', due_date: '' };

function TaskCard({ task, onMove, onProgress, onDelete }) {
  const idx = STATUS_ORDER.indexOf(task.status);
  return (
    <div className="bg-bg-soft border border-border-soft rounded-lg p-3 space-y-2">
      <div className="flex items-start justify-between gap-2">
        <div className="text-[13px] font-medium leading-snug">{task.title}</div>
        <button
          onClick={() => onDelete(task)}
          className="p-1 rounded text-muted hover:text-red hover:bg-red/10 shrink-0"
          title="Taak verwijderen"
        >
          <Trash2 className="w-3.5 h-3.5" />
        </button>
      </div>
      <div className="flex items-center gap-2 flex-wrap">
        <Badge color={STATUS_COLORS[task.priority] || 'muted'}>{PRIORITY_LABELS[task.priority] || task.priority}</Badge>
        {task.assignee_name && <span className="text-[11px] text-muted">{task.assignee_name}</span>}
        {task.due_date && <span className="text-[11px] text-muted">· {fmt.date(task.due_date)}</span>}
      </div>
      <div>
        <div className="flex items-center justify-between text-[10px] text-muted mb-1">
          <span>Voortgang</span>
          <span>{task.progress || 0}%</span>
        </div>
        <input
          type="range"
          min="0"
          max="100"
          step="5"
          value={task.progress || 0}
          onChange={e => onProgress(task, Number(e.target.value))}
          className="w-full h-1.5 accent-[#00d4ff] cursor-pointer"
        />
      </div>
      <div className="flex items-center justify-between pt-1">
        <button
          disabled={idx <= 0}
          onClick={() => onMove(task, STATUS_ORDER[idx - 1])}
          className="p-1 rounded text-muted hover:text-text hover:bg-card disabled:opacity-30 disabled:cursor-not-allowed"
          title="Naar vorige status"
        >
          <ChevronLeft className="w-4 h-4" />
        </button>
        <StatusBadge status={task.status} labels={{ todo: 'Te doen', in_progress: 'Bezig', done: 'Klaar' }} />
        <button
          disabled={idx >= STATUS_ORDER.length - 1}
          onClick={() => onMove(task, STATUS_ORDER[idx + 1])}
          className="p-1 rounded text-muted hover:text-text hover:bg-card disabled:opacity-30 disabled:cursor-not-allowed"
          title="Naar volgende status"
        >
          <ChevronRight className="w-4 h-4" />
        </button>
      </div>
    </div>
  );
}

export default function ProjectDetail() {
  const { id } = useParams();
  const navigate = useNavigate();
  const [data, setData] = useState(null);
  const [clients, setClients] = useState([]);
  const [users, setUsers] = useState([]);
  const [error, setError] = useState(null);

  const [editOpen, setEditOpen] = useState(false);
  const [taskOpen, setTaskOpen] = useState(false);
  const [taskForm, setTaskForm] = useState(EMPTY_TASK);
  const [taskSaving, setTaskSaving] = useState(false);
  const [taskError, setTaskError] = useState(null);

  const load = () => {
    setError(null);
    api.get(`/projects/${id}`).then(setData).catch(setError);
  };
  useEffect(load, [id]);
  useEffect(() => {
    api.get('/clients').then(setClients).catch(() => {});
    api.get('/users').then(setUsers).catch(() => {}); // admin-only: stil negeren
  }, []);

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

  const { project, tasks, milestones } = data;
  const doneCount = tasks.filter(t => t.status === 'done').length;
  const pct = tasks.length > 0 ? Math.round((doneCount / tasks.length) * 100) : 0;

  const moveTask = async (task, status) => {
    try {
      await api.post(`/projects/tasks/${task.id}/status`, { status });
      load();
    } catch (e) {
      alert(e.message);
    }
  };

  const setProgress = async (task, progress) => {
    // optimistisch bijwerken
    setData(d => ({ ...d, tasks: d.tasks.map(t => t.id === task.id ? { ...t, progress } : t) }));
    try {
      await api.post(`/projects/tasks/${task.id}/progress`, { progress });
    } catch (e) {
      alert(e.message);
      load();
    }
  };

  const deleteTask = async (task) => {
    if (!window.confirm(`Taak "${task.title}" verwijderen?`)) return;
    try {
      await api.del(`/projects/tasks/${task.id}`);
      load();
    } catch (e) {
      alert(e.message);
    }
  };

  const deleteProject = async () => {
    if (!window.confirm(`Project "${project.name}" en alle bijbehorende taken verwijderen?`)) return;
    try {
      await api.del(`/projects/${project.id}`);
      navigate('/projects');
    } catch (e) {
      alert(e.message);
    }
  };

  const saveTask = async () => {
    if (!taskForm.title.trim()) return setTaskError('Titel is verplicht');
    setTaskSaving(true);
    setTaskError(null);
    try {
      await api.post(`/projects/${id}/tasks`, {
        ...taskForm,
        assignee_id: taskForm.assignee_id || null,
        due_date: taskForm.due_date || null
      });
      setTaskOpen(false);
      setTaskForm(EMPTY_TASK);
      load();
    } catch (e) {
      setTaskError(e.message);
    } finally {
      setTaskSaving(false);
    }
  };

  return (
    <div className="space-y-5 fade-in">
      {/* Header */}
      <div>
        <Link to="/projects" className="inline-flex items-center gap-1 text-[12px] text-muted hover:text-accent mb-2">
          <ArrowLeft className="w-3.5 h-3.5" /> Terug naar projecten
        </Link>
        <div className="flex items-start justify-between gap-3 flex-wrap">
          <div className="min-w-0">
            <h1 className="text-xl font-bold tracking-tight">{project.name}</h1>
            <div className="flex items-center gap-2 mt-1.5 flex-wrap">
              {project.client_id ? (
                <Link to={`/clients/${project.client_id}`} className="text-[13px] text-accent hover:underline">
                  {project.client_name}
                </Link>
              ) : (
                <span className="text-[13px] text-muted">Geen cliënt</span>
              )}
              <StatusBadge status={project.status} labels={PROJECT_STATUS_LABELS} />
              <Badge color={STATUS_COLORS[project.priority] || 'muted'}>{PRIORITY_LABELS[project.priority] || project.priority}</Badge>
              <span className="text-[12px] text-muted">{fmt.date(project.start_date)} — {fmt.date(project.end_date)}</span>
              {project.budget != null && <span className="text-[12px] font-medium">{fmt.euro(project.budget)}</span>}
            </div>
            {project.description && <p className="text-[13px] text-muted mt-2 max-w-2xl">{project.description}</p>}
          </div>
          <div className="flex items-center gap-2 shrink-0">
            <Btn variant="secondary" size="sm" onClick={() => setEditOpen(true)}><Pencil className="w-3.5 h-3.5" /> Bewerken</Btn>
            <Btn variant="danger" size="sm" onClick={deleteProject}><Trash2 className="w-3.5 h-3.5" /> Verwijderen</Btn>
          </div>
        </div>

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

      {/* Kanban */}
      <div>
        <div className="flex items-center justify-between mb-3">
          <h2 className="text-[15px] font-semibold">Taken</h2>
          <Btn size="sm" onClick={() => { setTaskForm(EMPTY_TASK); setTaskError(null); setTaskOpen(true); }}>
            <Plus className="w-3.5 h-3.5" /> Taak toevoegen
          </Btn>
        </div>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
          {COLUMNS.map(col => {
            const colTasks = tasks.filter(t => t.status === col.key);
            return (
              <div key={col.key} className="bg-card border border-border-soft rounded-xl p-3">
                <div className="flex items-center justify-between px-1 pb-2">
                  <span className="text-[12px] font-semibold uppercase tracking-wide text-muted">{col.label}</span>
                  <span className="text-[11px] text-muted">{colTasks.length}</span>
                </div>
                <div className="space-y-2">
                  {colTasks.length === 0 ? (
                    <div className="text-[12px] text-muted text-center py-6">Geen taken</div>
                  ) : (
                    colTasks.map(t => (
                      <TaskCard key={t.id} task={t} onMove={moveTask} onProgress={setProgress} onDelete={deleteTask} />
                    ))
                  )}
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Milestones */}
      {milestones.length > 0 && (
        <Card title="Milestones" subtitle={`${milestones.length} mijlpaal${milestones.length === 1 ? '' : 'en'}`}>
          <div className="space-y-2">
            {milestones.map(m => (
              <div key={m.id} className="flex items-center justify-between gap-2 px-2.5 py-2 rounded-lg hover:bg-card-hover">
                <div className="flex items-center gap-2.5 min-w-0">
                  <Flag className="w-4 h-4 text-accent shrink-0" />
                  <span className="text-[13px] font-medium truncate">{m.name}</span>
                </div>
                <div className="flex items-center gap-3 shrink-0">
                  <span className="text-[12px] text-muted">{fmt.date(m.target_date)}</span>
                  <StatusBadge status={m.status} labels={MILESTONE_LABELS} />
                </div>
              </div>
            ))}
          </div>
        </Card>
      )}

      {/* Project bewerken */}
      <ProjectModal
        open={editOpen}
        onClose={() => setEditOpen(false)}
        clients={clients}
        project={project}
        onSaved={load}
      />

      {/* Taak toevoegen */}
      <Modal open={taskOpen} onClose={() => setTaskOpen(false)} title="Taak toevoegen">
        <div className="space-y-3">
          <Field label="Titel *">
            <input className={inputCls} value={taskForm.title} onChange={e => setTaskForm(f => ({ ...f, title: e.target.value }))} placeholder="Bijv. inventarisatie uitvoeren" />
          </Field>
          <Field label="Beschrijving">
            <textarea className={inputCls} rows={3} value={taskForm.description} onChange={e => setTaskForm(f => ({ ...f, description: e.target.value }))} />
          </Field>
          <div className="grid grid-cols-2 gap-3">
            <Field label="Toegewezen aan">
              <select className={inputCls} value={taskForm.assignee_id} onChange={e => setTaskForm(f => ({ ...f, assignee_id: e.target.value }))}>
                <option value="">— Niemand —</option>
                {users.map(u => <option key={u.id} value={u.id}>{u.username}</option>)}
              </select>
            </Field>
            <Field label="Prioriteit">
              <select className={inputCls} value={taskForm.priority} onChange={e => setTaskForm(f => ({ ...f, priority: e.target.value }))}>
                {Object.entries(PRIORITY_LABELS).map(([k, l]) => <option key={k} value={k}>{l}</option>)}
              </select>
            </Field>
          </div>
          <Field label="Deadline">
            <input type="date" className={inputCls} value={taskForm.due_date} onChange={e => setTaskForm(f => ({ ...f, due_date: e.target.value }))} />
          </Field>
        </div>
        {taskError && <div className="text-red text-[12px] mt-3">{taskError}</div>}
        <div className="flex justify-end gap-2 mt-4">
          <Btn variant="secondary" onClick={() => setTaskOpen(false)}>Annuleren</Btn>
          <Btn onClick={saveTask} loading={taskSaving}>Toevoegen</Btn>
        </div>
      </Modal>
    </div>
  );
}
