'use client';

import { useEffect, useMemo, useState } from 'react';
import { Plus, Clock, CheckCircle2, AlertTriangle, Paperclip } from 'lucide-react';
import { useAuth } from '@/lib/auth-context';
import { adminApiFetch } from '@/lib/api';
import { useToast } from '@/lib/toast';
import { useLiveRefresh } from '@/lib/realtime';
import AttachmentPicker, { Attachment } from '@/components/AttachmentPicker';
import AiPolishButton from '@/components/AiPolishButton';
import Modal from '@/components/Modal';
import { TableSkeleton } from '@/components/Skeletons';

type Member = { id: number; name: string; role: string };
type Task = {
  id: number; title: string; description: string | null; priority: string; status: string; dueAt: string;
  submittedAt: string | null; submissionNote: string | null; reviewNote: string | null; isOverdue: boolean; submittedLate: boolean;
  creator: { id: number; name: string }; assignee: { id: number; name: string };
  attachments: { id: number; kind: string; filename: string; url: string; uploadedBy: { name: string } }[];
};
type Comment = { id: number; body: string; createdAt: string; author: { name: string } };

const STATUS_STYLE: Record<string, string> = {
  ASSIGNED: 'bg-gray-100 text-gray-700', IN_PROGRESS: 'bg-blue-100 text-blue-700', SUBMITTED: 'bg-amber-100 text-amber-700',
  CHANGES_REQUESTED: 'bg-orange-100 text-orange-700', APPROVED: 'bg-green-100 text-green-700', CANCELLED: 'bg-gray-100 text-gray-400',
};
const emptyForm = { title: '', description: '', assigneeId: '', priority: 'MEDIUM', dueAt: '' };

export default function TasksPage() {
  const { accessToken, appSecretProof, user } = useAuth();
  const { show } = useToast();
  const [view, setView] = useState<'mine' | 'given' | 'all'>('mine');
  const [tasks, setTasks] = useState<Task[]>([]);
  const [members, setMembers] = useState<Member[]>([]);
  const [loading, setLoading] = useState(true);
  const [creating, setCreating] = useState(false);
  const [form, setForm] = useState(emptyForm);
  const [briefFiles, setBriefFiles] = useState<Attachment[]>([]);
  const [openId, setOpenId] = useState<number | null>(null);

  async function load() {
    if (!accessToken || !appSecretProof) return;
    setLoading(true);
    try {
      const [t, m] = await Promise.all([
        adminApiFetch(`/admin/tasks?view=${view}`, accessToken, appSecretProof),
        adminApiFetch('/admin/tasks/members', accessToken, appSecretProof),
      ]);
      setTasks(t.tasks || []); setMembers(m.members || []);
    } finally { setLoading(false); }
  }
  useEffect(() => { load(); }, [accessToken, appSecretProof, view]); // eslint-disable-line react-hooks/exhaustive-deps
  useLiveRefresh(['tasks'], load);

  useEffect(() => {
    const p = new URLSearchParams(window.location.search).get('open');
    if (p) setOpenId(Number(p));
  }, []);

  async function createTask(e: React.FormEvent) {
    e.preventDefault();
    if (!accessToken || !appSecretProof || !form.assigneeId || !form.dueAt) return;
    try {
      await adminApiFetch('/admin/tasks', accessToken, appSecretProof, {
        method: 'POST',
        body: JSON.stringify({ ...form, assigneeId: Number(form.assigneeId), dueAt: new Date(form.dueAt).toISOString(), attachments: briefFiles }),
      });
      show('success', 'Task assigned.');
      setForm(emptyForm); setBriefFiles([]); setCreating(false); load();
    } catch { show('error', 'Could not create that task.'); }
  }

  const open = tasks.find((t) => t.id === openId) || null;

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h1 className="text-xl font-bold">Tasks</h1>
        <button onClick={() => setCreating(true)} className="flex items-center gap-1.5 bg-brand-red text-white text-xs font-semibold px-3 py-2 rounded-lg"><Plus size={14} /> Assign a task</button>
      </div>

      <div className="flex gap-1">
        {(['mine', 'given', 'all'] as const).map((v) => (
          <button key={v} onClick={() => setView(v)} className={`text-xs font-semibold px-3 py-1.5 rounded-lg ${view === v ? 'bg-brand-charcoal text-white' : 'bg-white border border-brand-border text-gray-600'}`}>
            {v === 'mine' ? 'Assigned to me' : v === 'given' ? 'I assigned' : 'Everyone'}
          </button>
        ))}
      </div>

      {loading ? <TableSkeleton rows={5} cols={5} /> : (
        <div className="grid gap-2">
          {tasks.map((t) => (
            <button key={t.id} onClick={() => setOpenId(t.id)} className="text-left bg-white border border-brand-border rounded-xl p-4 hover:shadow-md transition-shadow">
              <div className="flex justify-between items-start gap-3">
                <div className="min-w-0">
                  <p className="text-sm font-semibold truncate">{t.title}</p>
                  <p className="text-[11px] text-gray-500 mt-0.5">{t.creator.name} → {t.assignee.name} &bull; {t.priority}</p>
                </div>
                <span className={`text-[10px] font-semibold px-2 py-0.5 rounded-full shrink-0 ${STATUS_STYLE[t.status]}`}>{t.status.replace('_', ' ')}</span>
              </div>
              <div className="flex items-center gap-3 mt-2 text-[11px] text-gray-400">
                <span className={`flex items-center gap-1 ${t.isOverdue ? 'text-brand-red font-semibold' : ''}`}><Clock size={11} /> Due {new Date(t.dueAt).toLocaleString('en-GB')}</span>
                {t.isOverdue && <span className="flex items-center gap-1 text-brand-red"><AlertTriangle size={11} /> Overdue</span>}
                {t.attachments.length > 0 && <span className="flex items-center gap-1"><Paperclip size={11} /> {t.attachments.length}</span>}
              </div>
            </button>
          ))}
          {tasks.length === 0 && <p className="text-sm text-gray-400">Nothing here.</p>}
        </div>
      )}

      {creating && (
        <Modal title="Assign a task" onClose={() => setCreating(false)} wide>
          <form onSubmit={createTask} className="space-y-3">
            <input required placeholder="Task title" value={form.title} onChange={(e) => setForm({ ...form, title: e.target.value })} className="w-full border border-brand-border rounded-lg px-3 py-2 text-sm" />
            <textarea placeholder="What exactly needs to be done" value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} rows={5} className="w-full border border-brand-border rounded-lg px-3 py-2 text-sm" />
            <AiPolishButton text={form.description} kind="task" onAccept={(t) => setForm((f) => ({ ...f, description: t }))} />
            <div className="grid grid-cols-3 gap-2">
              <select required value={form.assigneeId} onChange={(e) => setForm({ ...form, assigneeId: e.target.value })} className="border border-brand-border rounded-lg px-2 py-2 text-sm">
                <option value="">Give to…</option>
                {members.filter((m) => m.id !== user?.id).map((m) => <option key={m.id} value={m.id}>{m.name} ({m.role})</option>)}
              </select>
              <select value={form.priority} onChange={(e) => setForm({ ...form, priority: e.target.value })} className="border border-brand-border rounded-lg px-2 py-2 text-sm">
                {['LOW', 'MEDIUM', 'HIGH', 'URGENT'].map((p) => <option key={p} value={p}>{p}</option>)}
              </select>
              <input required type="datetime-local" value={form.dueAt} onChange={(e) => setForm({ ...form, dueAt: e.target.value })} className="border border-brand-border rounded-lg px-2 py-2 text-sm" />
            </div>
            <AttachmentPicker attachments={briefFiles} onChange={setBriefFiles} />
            <button className="w-full bg-brand-red text-white text-sm font-semibold py-2.5 rounded-lg">Assign task</button>
          </form>
        </Modal>
      )}

      {open && <TaskDetail task={open} onClose={() => setOpenId(null)} onChanged={load} isGiver={open.creator.id === user?.id} isReceiver={open.assignee.id === user?.id} />}
    </div>
  );
}

function TaskDetail({ task, onClose, onChanged, isGiver, isReceiver }: { task: Task; onClose: () => void; onChanged: () => void; isGiver: boolean; isReceiver: boolean }) {
  const { accessToken, appSecretProof } = useAuth();
  const { show } = useToast();
  const [comments, setComments] = useState<Comment[]>([]);
  const [comment, setComment] = useState('');
  const [submitNote, setSubmitNote] = useState('');
  const [submitFiles, setSubmitFiles] = useState<Attachment[]>([]);
  const [reviewNote, setReviewNote] = useState('');

  useEffect(() => {
    if (!accessToken || !appSecretProof) return;
    adminApiFetch(`/admin/tasks/${task.id}`, accessToken, appSecretProof).then((d) => setComments(d.comments || [])).catch(() => null);
  }, [task.id, accessToken, appSecretProof]);

  async function act(path: string, body?: unknown) {
    if (!accessToken || !appSecretProof) return;
    try { await adminApiFetch(`/admin/tasks/${task.id}${path}`, accessToken, appSecretProof, { method: 'POST', body: body ? JSON.stringify(body) : undefined }); onChanged(); }
    catch { show('error', 'That action failed.'); }
  }
  async function addComment(e: React.FormEvent) {
    e.preventDefault(); if (!comment.trim() || !accessToken || !appSecretProof) return;
    await adminApiFetch(`/admin/tasks/${task.id}/comments`, accessToken, appSecretProof, { method: 'POST', body: JSON.stringify({ body: comment }) });
    setComment(''); const d = await adminApiFetch(`/admin/tasks/${task.id}`, accessToken, appSecretProof); setComments(d.comments || []);
  }

  return (
    <Modal title={task.title} onClose={onClose} wide>
      <div className="space-y-3 text-sm">
        <p className="text-gray-600 whitespace-pre-wrap">{task.description || 'No description.'}</p>
        <p className="text-xs text-gray-400">{task.creator.name} → {task.assignee.name} &bull; Due {new Date(task.dueAt).toLocaleString('en-GB')} &bull; {task.priority}</p>

        {task.attachments.filter((a) => a.kind === 'BRIEF').length > 0 && (
          <div><p className="text-xs font-semibold mb-1">Brief attachments</p>
            <div className="flex flex-wrap gap-1.5">{task.attachments.filter((a) => a.kind === 'BRIEF').map((a) => <a key={a.id} href={a.url} target="_blank" rel="noreferrer" className="text-[11px] border border-brand-border rounded-full px-2 py-1 bg-brand-bg">{a.filename}</a>)}</div>
          </div>
        )}

        {isReceiver && (task.status === 'ASSIGNED' || task.status === 'CHANGES_REQUESTED') && (
          <button onClick={() => act('/start')} className="bg-brand-charcoal text-white text-xs font-semibold px-3 py-2 rounded-lg">Start working on this</button>
        )}

        {isReceiver && (task.status === 'IN_PROGRESS' || task.status === 'CHANGES_REQUESTED') && (
          <div className="border border-brand-border rounded-xl p-3 space-y-2">
            <p className="text-xs font-semibold">Submit your work</p>
            <textarea placeholder="Describe what you're submitting" value={submitNote} onChange={(e) => setSubmitNote(e.target.value)} rows={3} className="w-full border border-brand-border rounded-lg px-3 py-2 text-sm" />
            <AttachmentPicker attachments={submitFiles} onChange={setSubmitFiles} />
            <button onClick={() => act('/submit', { note: submitNote, attachments: submitFiles })} className="bg-brand-red text-white text-xs font-semibold px-3 py-2 rounded-lg">Submit for review</button>
          </div>
        )}

        {task.status === 'SUBMITTED' && (
          <div className="border border-brand-border rounded-xl p-3 space-y-2 bg-amber-50/40">
            <p className="text-xs font-semibold">Submitted{task.submittedLate ? ' (late)' : ''}: {task.submissionNote}</p>
            <div className="flex flex-wrap gap-1.5">{task.attachments.filter((a) => a.kind === 'SUBMISSION').map((a) => <a key={a.id} href={a.url} target="_blank" rel="noreferrer" className="text-[11px] border border-brand-border rounded-full px-2 py-1 bg-white">{a.filename}</a>)}</div>
            {isGiver && (
              <>
                <textarea placeholder="Feedback (required if requesting changes)" value={reviewNote} onChange={(e) => setReviewNote(e.target.value)} rows={2} className="w-full border border-brand-border rounded-lg px-3 py-2 text-sm" />
                <div className="flex gap-2">
                  <button onClick={() => act('/review', { decision: 'APPROVE', note: reviewNote })} className="flex items-center gap-1 bg-green-600 text-white text-xs font-semibold px-3 py-2 rounded-lg"><CheckCircle2 size={13} /> Approve</button>
                  <button onClick={() => act('/review', { decision: 'REQUEST_CHANGES', note: reviewNote })} className="bg-white border border-brand-border text-xs font-semibold px-3 py-2 rounded-lg">Request changes</button>
                </div>
              </>
            )}
          </div>
        )}

        {task.status === 'APPROVED' && <p className="text-xs text-green-700 font-semibold flex items-center gap-1"><CheckCircle2 size={13} /> Approved{task.reviewNote ? `: ${task.reviewNote}` : ''}</p>}

        <div className="border-t border-brand-border pt-3">
          <p className="text-xs font-semibold mb-2">Discussion</p>
          <div className="space-y-2 max-h-40 overflow-y-auto mb-2">
            {comments.map((c) => <p key={c.id} className="text-xs"><strong>{c.author.name}:</strong> {c.body}</p>)}
            {comments.length === 0 && <p className="text-xs text-gray-400">No comments yet.</p>}
          </div>
          <form onSubmit={addComment} className="flex gap-2">
            <input value={comment} onChange={(e) => setComment(e.target.value)} placeholder="Add a comment…" className="flex-1 border border-brand-border rounded-lg px-3 py-1.5 text-sm" />
            <button className="bg-brand-charcoal text-white text-xs font-semibold px-3 rounded-lg">Send</button>
          </form>
        </div>
      </div>
    </Modal>
  );
}
