'use client';

import React, { useState } from 'react';
import { App, Button, Checkbox, DatePicker, Empty, Form, Input, Select, Tag } from 'antd';
import dayjs from 'dayjs';
import { Icon } from '../ui/Icon';
import { UserAvatar } from '../ui/UserAvatar';
import { ApiError } from '../../lib/api';
import type { DirectoryUser } from '../../lib/leads';
import type { ProjectDetailRecord } from '../../lib/projects';
import { tasksApi } from '../../lib/tasks';

interface NewTaskValues {
  title: string;
  ownerId?: string;
  milestoneId?: string;
  dueDate: dayjs.Dayjs;
}

export interface ProjectTasksPanelProps {
  project: ProjectDetailRecord;
  people: DirectoryUser[];
  onChanged: () => void;
}

/** Lists a project's tasks with quick add and complete actions. */
export function ProjectTasksPanel({ project, people, onChanged }: ProjectTasksPanelProps) {
  const { message } = App.useApp();
  const [adding, setAdding] = useState(false);
  const [saving, setSaving] = useState(false);
  const [busyId, setBusyId] = useState<string | null>(null);
  const today = dayjs().startOf('day');

  const toggle = async (id: string) => {
    setBusyId(id);
    try {
      await tasksApi.toggle(id);
      onChanged();
    } catch (err) {
      message.error(err instanceof ApiError ? err.message : 'The task could not be updated');
    } finally {
      setBusyId(null);
    }
  };

  const create = async (values: NewTaskValues) => {
    setSaving(true);
    try {
      await tasksApi.create({
        title: values.title.trim(),
        ownerId: values.ownerId,
        dueDate: values.dueDate.endOf('day').toISOString(),
        projectId: project.id,
        milestoneId: values.milestoneId,
      });
      message.success('Task added');
      setAdding(false);
      onChanged();
    } catch (err) {
      message.error(err instanceof ApiError ? err.message : 'The task could not be added');
    } finally {
      setSaving(false);
    }
  };

  const tasks = project.tasks ?? [];
  const openCount = tasks.filter((t) => !t.completed).length;

  return (
    <div className="mt-2">
      <div className="mb-4 flex flex-wrap items-center justify-between gap-3">
        <div>
          <h3 className="m-0 text-[15px] font-semibold text-[var(--tcx-text)]">Project tasks</h3>
          <p className="m-0 mt-0.5 text-[12.5px] text-[var(--tcx-muted)]">
            {openCount} open of {tasks.length}
          </p>
        </div>
        {!adding && (
          <Button icon={<Icon name="plus" size={14} />} onClick={() => setAdding(true)}>
            Add task
          </Button>
        )}
      </div>

      {adding && <NewTaskForm project={project} people={people} saving={saving} onCancel={() => setAdding(false)} onSubmit={(v) => void create(v)} />}

      {tasks.length === 0 ? (
        <Empty description="No tasks yet. Add the work items for this project." />
      ) : (
        <ul className="m-0 list-none divide-y divide-[var(--tcx-border)] p-0">
          {tasks.map((t) => {
            const overdue = !t.completed && dayjs(t.dueDate).isBefore(today);
            return (
              <li key={t.id} className="flex flex-wrap items-center gap-3 py-3">
                <Checkbox checked={t.completed} disabled={busyId === t.id} onChange={() => void toggle(t.id)} aria-label={`Mark ${t.title} ${t.completed ? 'open' : 'done'}`} />
                <div className="min-w-0 flex-1">
                  <div className={`text-[14px] font-medium ${t.completed ? 'text-[var(--tcx-muted)] line-through' : 'text-[var(--tcx-text)]'}`}>{t.title}</div>
                  {t.milestone ? <div className="text-[12px] text-[var(--tcx-muted)]">Milestone: {t.milestone.title}</div> : null}
                </div>
                {t.owner ? (
                  <span className="flex items-center gap-1.5 text-[13px] text-[var(--tcx-text-2)]">
                    <UserAvatar name={t.owner.name} size={22} />
                    {t.owner.name}
                  </span>
                ) : null}
                <span className={`whitespace-nowrap text-[13px] ${overdue ? 'font-semibold text-rose-600 dark:text-rose-400' : 'text-[var(--tcx-text-2)]'}`}>{dayjs(t.dueDate).format('D MMM YYYY')}</span>
                {overdue ? (
                  <Tag color="red" className="m-0 rounded-full border-0">
                    Overdue
                  </Tag>
                ) : null}
              </li>
            );
          })}
        </ul>
      )}
    </div>
  );
}

function NewTaskForm({ project, people, saving, onCancel, onSubmit }: { project: ProjectDetailRecord; people: DirectoryUser[]; saving: boolean; onCancel: () => void; onSubmit: (v: NewTaskValues) => void }) {
  const [form] = Form.useForm<NewTaskValues>();
  return (
    <Form<NewTaskValues> form={form} layout="vertical" className="tcx-surface-card mb-4 p-4" initialValues={{ dueDate: dayjs().add(3, 'day'), ownerId: project.ownerId }} onFinish={onSubmit}>
      <div className="grid grid-cols-1 gap-x-4 sm:grid-cols-2">
        <Form.Item name="title" label="Task" className="sm:col-span-2" rules={[{ required: true, whitespace: true, message: 'Enter a task title' }]}>
          <Input placeholder="Enter task title" maxLength={255} autoFocus />
        </Form.Item>
        <Form.Item name="ownerId" label="Assigned to">
          <Select showSearch optionFilterProp="label" options={people.map((p) => ({ value: p.id, label: p.name }))} />
        </Form.Item>
        <Form.Item name="dueDate" label="Due date" rules={[{ required: true, message: 'Choose a due date' }]}>
          <DatePicker className="w-full" />
        </Form.Item>
        <Form.Item name="milestoneId" label="Milestone" className="sm:col-span-2">
          <Select allowClear placeholder="No milestone" options={(project.milestones ?? []).map((m) => ({ value: m.id, label: m.title }))} />
        </Form.Item>
      </div>
      <div className="flex justify-end gap-2">
        <Button type="text" onClick={onCancel}>
          Cancel
        </Button>
        <Button type="primary" htmlType="submit" loading={saving}>
          Add task
        </Button>
      </div>
    </Form>
  );
}
