import React, { useMemo, useState, useEffect } from 'react';
import { useParams, useNavigate, useSearchParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import {
  FaArrowLeft, FaSave, FaEdit, FaTimes, FaCheckCircle,
  FaTimesCircle, FaSpinner, FaTasks, FaCalendarAlt,
  FaFileAlt, FaLink, FaMoneyBillWave, FaInfoCircle,
  FaPlus, FaTrash, FaChevronDown, FaChevronRight, FaClock, FaSitemap, FaBullhorn,
  FaMicrophone,
} from 'react-icons/fa';
import { toast, ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { useTaskDetails, useProjectMutations } from '../hooks/useProject';
import projectService, {
  serializeProgressUpdateRows,
  CUSTOM_TASK_UPDATES,
  type ProgressUpdateChildRow,
} from '../services/projectService';
import LinkField from '../components/LinkField';
import type { Task } from '../services/projectService';
import ActivityLog from '../components/ActivityLog';
import { DEFAULT_COMPANY, formatOrgCurrencyAmount } from '../constants/orgDefaults';
import VoiceTaskUpdateModal from '../components/VoiceTaskUpdateModal';

const TASK_ACTION_OPTIONS = [
  'Open',
  'Raised',
  'Warning',
  'Penalty',
  'Change Requests',
  'Problems',
  'Letter',
] as const;

// ─── Collapsible Section ─────────────────────────────────────────────────────
const CollapsibleSection: React.FC<{
  title: string;
  icon?: React.ReactNode;
  defaultOpen?: boolean;
  children: React.ReactNode;
  headerExtra?: React.ReactNode;
}> = ({ title, icon, defaultOpen = true, children, headerExtra }) => {
  const [open, setOpen] = useState(defaultOpen);
  return (
    <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden shadow-sm">
      <div className="flex items-center justify-between px-5 py-3.5 hover:bg-gray-50 dark:hover:bg-gray-700/30 transition-colors">
        <button
          type="button"
          onClick={() => setOpen(o => !o)}
          className="flex items-center gap-2 text-sm font-semibold text-gray-700 dark:text-gray-200 flex-1 text-left"
        >
          {icon}
          <span>{title}</span>
        </button>
        <div className="flex items-center gap-2">
          {/* Extra content (e.g. Voice button) rendered alongside the chevron */}
          {headerExtra}
          <button type="button" onClick={() => setOpen(o => !o)}>
            {open
              ? <FaChevronDown className="text-gray-400 text-xs flex-shrink-0" />
              : <FaChevronRight className="text-gray-400 text-xs flex-shrink-0" />}
          </button>
        </div>
      </div>
      {open && (
        <div className="px-5 py-5 bg-white dark:bg-gray-800 border-t border-gray-100 dark:border-gray-700/50">
          {children}
        </div>
      )}
    </div>
  );
};

// ─── Field helpers ────────────────────────────────────────────────────────────
const FL: React.FC<{ children: React.ReactNode; required?: boolean }> = ({ children, required }) => (
  <label className="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">
    {children}{required && <span className="text-red-500 ml-0.5">*</span>}
  </label>
);

const RV: React.FC<{ children?: React.ReactNode }> = ({ children }) => (
  <div className="px-3 py-2 text-sm text-gray-800 dark:text-gray-200 bg-gray-50 dark:bg-gray-900/30 rounded-lg min-h-[36px] flex items-center border border-transparent">
    {children || <span className="text-gray-400 dark:text-gray-600">-</span>}
  </div>
);

// ─── Style helpers ────────────────────────────────────────────────────────────
const statusBadge = (s: string) => {
  switch (s?.toLowerCase()) {
    case 'open':           return 'bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-300';
    case 'working':        return 'bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-300';
    case 'pending review': return 'bg-purple-100 text-purple-800 dark:bg-purple-900/40 dark:text-purple-300';
    case 'completed':      return 'bg-green-100 text-green-800 dark:bg-green-900/40 dark:text-green-300';
    case 'cancelled':      return 'bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-400';
    case 'overdue':        return 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300';
    default:               return 'bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-400';
  }
};

const priorityBadge = (p: string) => {
  switch (p?.toLowerCase()) {
    case 'high':   return 'bg-red-100 text-red-800 dark:bg-red-900/40 dark:text-red-300';
    case 'medium': return 'bg-orange-100 text-orange-800 dark:bg-orange-900/40 dark:text-orange-300';
    case 'low':    return 'bg-green-100 text-green-800 dark:bg-green-900/40 dark:text-green-300';
    case 'urgent': return 'bg-red-200 text-red-900 dark:bg-red-800/50 dark:text-red-200';
    default:       return 'bg-gray-100 text-gray-600';
  }
};

const fmtDate = (d?: string) =>
  d ? new Date(d).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' }) : '-';
const fmtCurrency = formatOrgCurrencyAmount;

// ─── Component ────────────────────────────────────────────────────────────────
type DependsOnRow = { task?: string; subject?: string; idx?: number; _isNew?: boolean };

const TaskDetail: React.FC = () => {
  const { t } = useTranslation();
  const { taskName } = useParams<{ taskName: string }>();
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const isNew = taskName === 'new';
  const startInEditMode = useMemo(() => (!isNew && (searchParams.get('edit') || '') === '1'), [isNew, searchParams]);
  const duplicateFrom = useMemo(() => (isNew ? (searchParams.get('duplicate') || '') : ''), [isNew, searchParams]);
  const [isDuplicating, setIsDuplicating] = useState(false);

  const { task, loading, error, refetch } = useTaskDetails(isNew ? null : (taskName || null));
  const { createTask, updateTask, loading: saving } = useProjectMutations();
  const [isEditing, setIsEditing] = useState(isNew);

  // ── Voice Update Modal ──────────────────────────────────────────────────────
  const [showVoiceUpdateModal, setShowVoiceUpdateModal] = useState(false);

  // ─── Form state ────────────────────────────────────────────────────────────
  const prefillProject = isNew ? (searchParams.get('project') || '') : '';
  const emptyForm: Partial<Task> = {
    subject: '', project: prefillProject, status: 'Open', priority: 'Medium',
    task_weight: 0, is_group: 0, is_template: 0, is_milestone: 0,
    exp_start_date: '', exp_end_date: '', expected_time: 0, progress: 0,
    completed_on: '',
    custom_risk: '',
    custom_action: '',
    custom_task_obstacle: '',
    description: '', color: '', department: '', company: DEFAULT_COMPANY, parent_task: '',
    custom_assign_to: '',
  };
  const [form, setForm] = useState<Partial<Task>>(emptyForm);
  useEffect(() => { if (startInEditMode) setIsEditing(true); }, [startInEditMode]);

  // Duplicate: prefill new task form from an existing task
  useEffect(() => {
    if (!isNew) return;
    if (!duplicateFrom) return;
    let cancelled = false;
    setIsDuplicating(true);
    projectService
      .getTask(duplicateFrom)
      .then((t) => {
        if (cancelled) return;
        setForm((prev) => ({
          ...prev,
          ...t,
          name: '',
          subject: t.subject ? `${t.subject} (Copy)` : '',
          status: 'Open',
          progress: 0,
        }));
        const dupRows = ((t as any)[CUSTOM_TASK_UPDATES] || []) as ProgressUpdateChildRow[];
        setTaskProgressUpdates(dupRows.map(r => ({ update_: r.update_, date: r.date ? String(r.date).slice(0, 10) : '' })));
        setIsEditing(true);
      })
      .catch(() => {
        // ignore; keep empty form
      })
      .finally(() => {
        if (!cancelled) setIsDuplicating(false);
      });
    return () => { cancelled = true; };
  }, [isNew, duplicateFrom]);

  // depends_on child table managed separately
  const [dependsOn, setDependsOn] = useState<DependsOnRow[]>([]);
  /** `custom_task_updates` — Task column is stored but not shown; filled with task name on save. */
  const [taskProgressUpdates, setTaskProgressUpdates] = useState<ProgressUpdateChildRow[]>([]);

  // ─── Hierarchy: parent task details ────────────────────────────────────────
  const [parentTaskInfo, setParentTaskInfo] = useState<{ subject?: string; status?: string } | null>(null);
  useEffect(() => {
    if (form.parent_task) {
      projectService.getTask(form.parent_task)
        .then(t => setParentTaskInfo({ subject: t.subject, status: t.status }))
        .catch(() => setParentTaskInfo({}));
    } else {
      setParentTaskInfo(null);
    }
  }, [form.parent_task]);

  const syncForm = (t: Task) => {
    setForm({
      subject:       t.subject || '',
      project:       t.project || '',
      status:        t.status || 'Open',
      priority:      t.priority || 'Medium',
      task_weight:   t.task_weight ?? 0,
      is_group:      t.is_group ?? 0,
      is_template:   t.is_template ?? 0,
      is_milestone:  t.is_milestone ?? 0,
      exp_start_date: t.exp_start_date || '',
      exp_end_date:  t.exp_end_date || '',
      expected_time: t.expected_time ?? 0,
      progress:      t.progress ?? 0,
      description:   t.description || '',
      color:         t.color || '',
      department:    t.department || '',
      company:       t.company || DEFAULT_COMPANY,
      parent_task:   t.parent_task || '',
      custom_assign_to: t.custom_assign_to || '',
      completed_on:  t.completed_on ? String(t.completed_on).slice(0, 10) : '',
      custom_risk:   t.custom_risk || '',
      custom_action: t.custom_action || '',
      custom_task_obstacle: t.custom_task_obstacle || '',
    });
    setDependsOn(t.depends_on || []);
    setTaskProgressUpdates(
      (((t as any)[CUSTOM_TASK_UPDATES] || []) as ProgressUpdateChildRow[]).map(r => ({
        name: r.name,
        update_: r.update_,
        date: r.date ? String(r.date).slice(0, 10) : '',
        task: r.task,
      })),
    );
  };

  useEffect(() => { if (task && !isNew) syncForm(task); }, [task, isNew]);
  useEffect(() => {
    if (isNew && !duplicateFrom) setTaskProgressUpdates([]);
  }, [isNew, duplicateFrom]);

  const set = (k: keyof Task, v: any) => setForm(f => ({ ...f, [k]: v }));
  const editable = isNew || isEditing;

  const inputCls = 'w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-amber-400 focus:outline-none';
  const selectCls = 'w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-amber-400 focus:outline-none';

  // ─── Depends-on handlers ───────────────────────────────────────────────────
  const addDependsOnRow = () => setDependsOn(prev => [...prev, { task: '', subject: '', _isNew: true }]);

  const updateDependsOnRow = async (idx: number, selectedTask: string) => {
    setDependsOn(prev => prev.map((row, i) => i === idx ? { ...row, task: selectedTask, subject: '' } : row));
    if (!selectedTask) return;
    try {
      const fetched = await projectService.getTask(selectedTask);
      setDependsOn(prev => prev.map((row, i) =>
        i === idx ? { ...row, task: selectedTask, subject: fetched.subject || selectedTask } : row
      ));
    } catch {
      // keep task name, subject stays empty
    }
  };

  const removeDependsOnRow = (idx: number) => {
    setDependsOn(prev => prev.filter((_, i) => i !== idx));
  };

  const addTaskProgressRow = () => setTaskProgressUpdates(prev => [...prev, {}]);
  const removeTaskProgressRow = (idx: number) => setTaskProgressUpdates(prev => prev.filter((_, i) => i !== idx));

  // ─── Voice update handler ──────────────────────────────────────────────────
  // Called by VoiceTaskUpdateModal after it successfully saves the row to Frappe.
  // We just refetch so the table reflects the new row.
  const handleVoiceUpdateSuccess = () => {
    refetch();
    toast.success('Voice update added!', { icon: <FaCheckCircle /> });
  };

  // ─── Save ──────────────────────────────────────────────────────────────────
  const handleSave = async () => {
    if (!form.subject?.trim()) {
      toast.error('Task Subject is required', { icon: <FaTimesCircle /> });
      return;
    }
    if (form.status === 'Completed' && !String(form.completed_on || '').trim()) {
      toast.error('Completed On: This field is mandatory', { icon: <FaTimesCircle /> });
      return;
    }
    try {
      const payload: Partial<Task> = {
        subject:       form.subject,
        project:       form.project || undefined,
        status:        form.status,
        priority:      form.priority,
        task_weight:   form.task_weight,
        is_group:      form.is_group,
        is_template:   form.is_template,
        is_milestone:  form.is_milestone,
        expected_time: form.expected_time,
        progress:      form.progress,
        description:   form.description,
        department:    form.department || undefined,
        company:       form.company || undefined,
        parent_task:   form.parent_task || undefined,
        custom_assign_to: form.custom_assign_to || undefined,
        depends_on:    dependsOn.filter(r => r.task).map((r, i) => ({
          task: r.task,
          idx:  i + 1,
        })),
        custom_risk:   form.custom_risk || undefined,
        custom_action: form.custom_action || undefined,
        custom_task_obstacle: form.custom_task_obstacle || undefined,
      };
      if (form.exp_start_date) payload.exp_start_date = form.exp_start_date;
      if (form.exp_end_date) payload.exp_end_date = form.exp_end_date;
      if (form.status === 'Completed') {
        payload.completed_on = form.completed_on;
      } else {
        (payload as Record<string, unknown>).completed_on = null;
      }

      if (isNew) {
        const created = await createTask(payload);
        const childPayload = serializeProgressUpdateRows(taskProgressUpdates, { fillTaskLink: created.name });
        if (childPayload.length) {
          await updateTask(created.name, { [CUSTOM_TASK_UPDATES]: childPayload as any });
        }
        toast.success('Task created', { icon: <FaCheckCircle /> });
        setIsEditing(false);
        navigate(`/projects/tasks/${created.name}`);
      } else {
        await updateTask(taskName!, {
          ...payload,
          [CUSTOM_TASK_UPDATES]: serializeProgressUpdateRows(taskProgressUpdates, { fillTaskLink: taskName! }) as any,
        });
        toast.success('Task saved', { icon: <FaCheckCircle /> });
        setIsEditing(false);
        refetch();
      }
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'Error saving task', { icon: <FaTimesCircle /> });
    }
  };

  const handleCancel = () => { if (task) syncForm(task); setIsEditing(false); };

  // ─── Loading / Error ───────────────────────────────────────────────────────
  if (loading && !isNew) {
    return <div className="flex items-center justify-center min-h-[400px]"><div className="animate-spin rounded-full h-12 w-12 border-b-2 border-amber-500" /></div>;
  }
  if (!isNew && (error || !task)) {
    return (
      <div className="p-6">
        <button onClick={() => navigate('/projects/tasks')} className="flex items-center gap-2 text-gray-600 mb-4 text-sm hover:text-gray-900">
          <FaArrowLeft /> Back to Tasks
        </button>
        <div className="p-4 bg-red-50 dark:bg-red-900/20 rounded-lg text-red-700 dark:text-red-300">{error || 'Task not found'}</div>
      </div>
    );
  }

  // ─── Render ────────────────────────────────────────────────────────────────
  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900">
      <ToastContainer position="top-right" autoClose={3500} />

      {/* ── Voice Task Update Modal ── */}
      {!isNew && taskName && (
        <VoiceTaskUpdateModal
          isOpen={showVoiceUpdateModal}
          onClose={() => setShowVoiceUpdateModal(false)}
          taskName={taskName}
          onUpdateSuccess={handleVoiceUpdateSuccess}
        />
      )}

      {/* ── Header strip ── */}
      <div className="bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 shadow-sm">
        <div className="px-6 py-4">
          {/* Breadcrumb */}
          <div className="flex items-center gap-1.5 text-xs mb-3 text-gray-400 dark:text-gray-500">
            <button onClick={() => navigate('/projects')} className="hover:text-amber-600 dark:hover:text-amber-400 transition-colors">
              {t('projects.moduleTitle', 'Project Management')}
            </button>
            <span>/</span>
            <button onClick={() => navigate('/projects/tasks')} className="hover:text-amber-600 dark:hover:text-amber-400 transition-colors">
              {t('projects.tasksDoctype', 'Tasks')}
            </button>
            <span>/</span>
            <span className="text-gray-600 dark:text-gray-300 font-medium">
              {isNew ? 'New Task' : (task?.subject || taskName)}
            </span>
          </div>
          <div className="flex flex-wrap items-start justify-between gap-4">
            <div className="flex items-start gap-3 min-w-0">
              <button onClick={() => navigate('/projects/tasks')} className="mt-1 text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 flex-shrink-0 transition-colors">
                <FaArrowLeft />
              </button>
              <div className="min-w-0">
                <div className="flex items-center gap-3 flex-wrap">
                  <div className="w-9 h-9 rounded-lg bg-amber-500 flex items-center justify-center flex-shrink-0 shadow-sm">
                    <FaTasks className="text-white text-sm" />
                  </div>
                  <div>
                    <h1 className="text-xl font-bold text-gray-900 dark:text-white leading-tight">
                      {isNew ? 'New Task' : (task?.subject || taskName)}
                    </h1>
                    {!isNew && <p className="text-xs text-gray-400 dark:text-gray-500">{taskName}</p>}
                  </div>
                </div>
                {!isNew && task && (
                  <div className="flex items-center flex-wrap gap-2 mt-2 ml-12">
                    <span className={`px-2.5 py-0.5 rounded-full text-xs font-semibold ${statusBadge(task.status || '')}`}>{task.status || 'Open'}</span>
                    <span className={`px-2.5 py-0.5 rounded-full text-xs font-semibold ${priorityBadge(task.priority || '')}`}>{task.priority || '-'}</span>
                    {task.project && (
                      <button onClick={() => navigate(`/projects/list/${task.project}`)} className="text-xs text-indigo-600 dark:text-indigo-400 border border-indigo-200 dark:border-indigo-700 rounded-full px-2.5 py-0.5 hover:underline">
                        {task.project}
                      </button>
                    )}
                    {task.progress !== undefined && task.progress > 0 && (
                      <div className="flex items-center gap-1.5 text-xs text-gray-500 dark:text-gray-400">
                        <div className="w-20 h-1.5 bg-gray-200 dark:bg-gray-600 rounded-full overflow-hidden">
                          <div className="h-full bg-amber-500 rounded-full" style={{ width: `${Math.min(task.progress, 100)}%` }} />
                        </div>
                        <span className="font-medium">{task.progress}%</span>
                      </div>
                    )}
                  </div>
                )}
              </div>
            </div>

            {/* Actions */}
            <div className="flex gap-2 flex-wrap flex-shrink-0">
              {!isNew && (
                <button
                  onClick={() => {
                    const params = new URLSearchParams();
                    if (task?.project) params.set('project', task.project);
                    params.set('task', task?.name || taskName || '');
                    navigate(`/projects/timesheets/new?${params.toString()}`);
                  }}
                  className="flex items-center gap-2 px-4 py-2 border border-green-500 text-green-600 dark:text-green-400 rounded-lg hover:bg-green-50 dark:hover:bg-green-900/20 text-sm transition-colors"
                  title="Create a timesheet for this task"
                >
                  <FaClock size={13} /> Create Timesheet
                </button>
              )}
              {!isEditing && !isNew && (
                <button onClick={() => setIsEditing(true)} className="flex items-center gap-2 px-4 py-2 bg-amber-500 text-white rounded-lg hover:bg-amber-600 text-sm transition-colors shadow-sm">
                  <FaEdit size={13} /> Edit
                </button>
              )}
              {(isEditing || isNew) && (
                <>
                  <button onClick={handleSave} disabled={saving} className="flex items-center gap-2 px-4 py-2 bg-amber-500 text-white rounded-lg hover:bg-amber-600 disabled:opacity-50 text-sm shadow-sm">
                    {saving ? <FaSpinner className="animate-spin" size={13} /> : <FaSave size={13} />}
                    {saving ? 'Saving…' : 'Save'}
                  </button>
                  {!isNew && (
                    <button onClick={handleCancel} className="flex items-center gap-1.5 px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-sm text-gray-600 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700/50">
                      <FaTimes size={13} /> Cancel
                    </button>
                  )}
                </>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* ── Form sections ── */}
      <div className="px-6 py-6 space-y-3">

        {/* ── 1. Main fields ── */}
        <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 shadow-sm px-5 py-5">
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-8 gap-y-4">
            <div className="sm:col-span-2">
              <FL required>Subject</FL>
              {editable
                ? <input type="text" value={form.subject || ''} onChange={e => set('subject', e.target.value)} className={inputCls} placeholder="Enter task subject" />
                : <RV>{form.subject}</RV>}
            </div>
            <div>
              <FL>Status</FL>
              {editable
                ? <select value={form.status || 'Open'} onChange={e => set('status', e.target.value)} className={selectCls}>
                    <option value="Open">Open</option>
                    <option value="Working">Working</option>
                    <option value="Pending Review">Pending Review</option>
                    <option value="Overdue">Overdue</option>
                    <option value="Template">Template</option>
                    <option value="Completed">Completed</option>
                    <option value="Cancelled">Cancelled</option>
                  </select>
                : <RV><span className={`px-2 py-0.5 rounded text-xs font-medium ${statusBadge(form.status || '')}`}>{form.status}</span></RV>}
            </div>
            {form.status === 'Completed' && (
              <div>
                <FL required>Completed On</FL>
                {editable
                  ? <input type="date" value={form.completed_on || ''} onChange={e => set('completed_on', e.target.value)} className={inputCls} />
                  : <RV>{fmtDate(form.completed_on)}</RV>}
              </div>
            )}
            <div>
              <FL>Project</FL>
              {editable
                ? <LinkField label="Project" hideLabel doctype="Project" value={form.project || ''} onChange={v => set('project', v)} placeholder="Link to project…" />
                : <RV>
                    {form.project
                      ? <button onClick={() => navigate(`/projects/list/${form.project}`)} className="text-indigo-600 dark:text-indigo-400 hover:underline">{form.project}</button>
                      : '-'}
                  </RV>}
            </div>
            <div>
              <FL>Risk</FL>
              {editable
                ? (
                  <select
                    value={form.custom_risk || ''}
                    onChange={e => set('custom_risk', e.target.value)}
                    className={selectCls}
                  >
                    <option value="">—</option>
                    <option value="Yes">Yes</option>
                    <option value="No">No</option>
                  </select>
                )
                : <RV>{form.custom_risk || '—'}</RV>}
            </div>
            <div>
              <FL>Action</FL>
              {editable
                ? (
                  <select
                    value={form.custom_action || ''}
                    onChange={e => set('custom_action', e.target.value)}
                    className={selectCls}
                  >
                    <option value="">—</option>
                    {TASK_ACTION_OPTIONS.map(opt => (
                      <option key={opt} value={opt}>{opt}</option>
                    ))}
                  </select>
                )
                : <RV>{form.custom_action || '—'}</RV>}
            </div>
            <div>
              <FL>Priority</FL>
              {editable
                ? <select value={form.priority || 'Medium'} onChange={e => set('priority', e.target.value)} className={selectCls}>
                    <option value="Low">Low</option>
                    <option value="Medium">Medium</option>
                    <option value="High">High</option>
                    <option value="Urgent">Urgent</option>
                  </select>
                : <RV><span className={`px-2 py-0.5 rounded text-xs font-medium ${priorityBadge(form.priority || '')}`}>{form.priority}</span></RV>}
            </div>
            <div>
              <FL>Weight</FL>
              {editable
                ? <input type="number" min={0} step={0.1} value={form.task_weight ?? 0} onChange={e => set('task_weight', parseFloat(e.target.value) || 0)} className={inputCls} />
                : <RV>{form.task_weight ?? 0}</RV>}
            </div>
            <div>
              <FL>Parent Task</FL>
              {editable
                ? <LinkField
                    label="Parent Task"
                    hideLabel
                    doctype="Task"
                    value={form.parent_task || ''}
                    onChange={v => set('parent_task', v)}
                    placeholder="Select parent task…"
                    filters={{ is_group: 1 }}
                  />
                : <RV>
                    {form.parent_task
                      ? <button onClick={() => navigate(`/projects/tasks/${form.parent_task}`)} className="text-indigo-600 dark:text-indigo-400 hover:underline">{form.parent_task}</button>
                      : '-'}
                  </RV>}
            </div>
            <div>
              <FL>Assign to</FL>
              {editable
                ? (
                  <LinkField
                    label="Assign to"
                    hideLabel
                    doctype="User"
                    value={form.custom_assign_to || ''}
                    onChange={v => set('custom_assign_to', v)}
                    placeholder="Select user…"
                  />
                )
                : <RV>{form.custom_assign_to || '—'}</RV>}
            </div>
            <div className="sm:col-span-2 flex flex-wrap gap-6 pt-1">
              {[
                { key: 'is_group' as keyof Task,    label: 'Is Group' },
                { key: 'is_template' as keyof Task, label: 'Is Template' },
              ].map(({ key, label }) => (
                <label key={key} className={`flex items-center gap-2 ${editable ? 'cursor-pointer' : 'cursor-default'}`}>
                  <input
                    type="checkbox"
                    checked={!!form[key]}
                    onChange={e => set(key, e.target.checked ? 1 : 0)}
                    disabled={!editable}
                    className="w-4 h-4 text-amber-500 border-gray-300 rounded focus:ring-amber-400"
                  />
                  <span className="text-sm text-gray-700 dark:text-gray-300 font-medium">{label}</span>
                </label>
              ))}
            </div>
          </div>
        </div>

        {/* ── 2. Timeline ── */}
        <CollapsibleSection title="Timeline" icon={<FaCalendarAlt className="text-indigo-500" size={13} />} defaultOpen={true}>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-8 gap-y-4">
            <div>
              <FL>Expected Start Date</FL>
              {editable
                ? <input type="date" value={form.exp_start_date || ''} onChange={e => set('exp_start_date', e.target.value)} className={inputCls} />
                : <RV>{fmtDate(form.exp_start_date)}</RV>}
            </div>
            <div>
              <FL>Expected End Date</FL>
              {editable
                ? <input type="date" value={form.exp_end_date || ''} onChange={e => set('exp_end_date', e.target.value)} className={inputCls} />
                : <RV>{fmtDate(form.exp_end_date)}</RV>}
            </div>
            <div>
              <FL>Expected Time (In hours)</FL>
              {editable
                ? <input type="number" min={0} step={0.5} value={form.expected_time ?? 0} onChange={e => set('expected_time', parseFloat(e.target.value) || 0)} className={inputCls} />
                : <RV>{form.expected_time ?? 0}</RV>}
            </div>
            <div>
              <FL>% Progress</FL>
              {editable
                ? <input type="number" min={0} max={100} value={form.progress ?? 0} onChange={e => set('progress', parseInt(e.target.value) || 0)} className={inputCls} />
                : <RV>
                    <div className="flex items-center gap-2 w-full">
                      <div className="flex-1 h-2 bg-gray-200 dark:bg-gray-600 rounded-full overflow-hidden">
                        <div className="h-full bg-amber-500 rounded-full" style={{ width: `${Math.min(form.progress ?? 0, 100)}%` }} />
                      </div>
                      <span className="text-sm font-medium min-w-[36px] text-right">{form.progress ?? 0}%</span>
                    </div>
                  </RV>}
            </div>
            <div className="sm:col-span-2">
              <label className={`flex items-center gap-2 ${editable ? 'cursor-pointer' : 'cursor-default'}`}>
                <input
                  type="checkbox"
                  checked={!!form.is_milestone}
                  onChange={e => set('is_milestone', e.target.checked ? 1 : 0)}
                  disabled={!editable}
                  className="w-4 h-4 text-amber-500 border-gray-300 rounded focus:ring-amber-400"
                />
                <span className="text-sm text-gray-700 dark:text-gray-300 font-medium">Is Milestone</span>
              </label>
            </div>
          </div>
        </CollapsibleSection>

        {/* ── 3. Task Updates — with Voice button in header ── */}
        <CollapsibleSection
          title="Task Updates"
          icon={<FaBullhorn className="text-violet-500" size={13} />}
          defaultOpen={true}
          headerExtra={
            // Only show for saved (non-new) tasks
            !isNew && taskName ? (
              <button
                type="button"
                onClick={(e) => {
                  e.stopPropagation(); // prevent collapsing the section
                  setShowVoiceUpdateModal(true);
                }}
                className="flex items-center gap-1.5 px-3 py-1 bg-purple-600 hover:bg-purple-700 text-white text-xs font-medium rounded-lg transition-colors shadow-sm"
                title="Add a voice update"
              >
                <FaMicrophone size={10} />
                Voice Update
              </button>
            ) : null
          }
        >
          <div className="rounded-lg border border-gray-200 dark:border-gray-700 overflow-hidden">
            <div className={`grid ${editable ? 'grid-cols-[40px_1fr_8rem_36px]' : 'grid-cols-[40px_1fr_8rem]'} bg-gray-50 dark:bg-gray-900/50 border-b border-gray-200 dark:border-gray-700`}>
              <div className="px-3 py-2 text-xs font-medium text-gray-500 uppercase">No.</div>
              <div className="px-3 py-2 text-xs font-medium text-gray-500 uppercase">Update</div>
              <div className="px-3 py-2 text-xs font-medium text-gray-500 uppercase">Date</div>
              {editable && <div className="py-2 w-9" />}
            </div>
            {taskProgressUpdates.length === 0 ? (
              <div className="py-8 text-center text-sm text-gray-400 italic">No updates yet.</div>
            ) : (
              <div className="divide-y divide-gray-100 dark:divide-gray-700">
                {taskProgressUpdates.map((row, idx) => (
                  <div key={row.name || `row-${idx}`} className={`grid ${editable ? 'grid-cols-[40px_1fr_8rem_36px]' : 'grid-cols-[40px_1fr_8rem]'} items-center hover:bg-gray-50/80 dark:hover:bg-gray-800/40`}>
                    <div className="px-3 py-2 text-xs text-gray-500 font-medium">{idx + 1}</div>
                    <div className="px-3 py-1.5 min-w-0">
                      {editable ? (
                        <input
                          type="text"
                          value={row.update_ || ''}
                          onChange={e => setTaskProgressUpdates(prev => prev.map((r, i) => (i === idx ? { ...r, update_: e.target.value } : r)))}
                          className={inputCls}
                          placeholder="Update text…"
                        />
                      ) : (
                        <span className="text-sm text-gray-800 dark:text-gray-200">{row.update_ || '—'}</span>
                      )}
                    </div>
                    <div className="px-3 py-1.5">
                      {editable ? (
                        <input
                          type="date"
                          value={row.date ? String(row.date).slice(0, 10) : ''}
                          onChange={e => setTaskProgressUpdates(prev => prev.map((r, i) => (i === idx ? { ...r, date: e.target.value } : r)))}
                          className={inputCls}
                        />
                      ) : (
                        <span className="text-sm text-gray-700 dark:text-gray-300">{row.date ? fmtDate(String(row.date).slice(0, 10)) : '—'}</span>
                      )}
                    </div>
                    {editable && (
                      <div className="flex justify-center">
                        <button
                          type="button"
                          onClick={() => removeTaskProgressRow(idx)}
                          className="p-1.5 text-red-400 hover:text-red-600 rounded transition-colors"
                          title="Remove row"
                        >
                          <FaTrash size={11} />
                        </button>
                      </div>
                    )}
                  </div>
                ))}
              </div>
            )}
            {editable && (
              <div className="border-t border-gray-200 dark:border-gray-700 px-3 py-2 bg-gray-50 dark:bg-gray-900/30">
                <button
                  type="button"
                  onClick={addTaskProgressRow}
                  className="flex items-center gap-1.5 text-xs text-blue-600 dark:text-blue-400 hover:text-blue-700 font-medium"
                >
                  <FaPlus size={10} /> Add Row
                </button>
              </div>
            )}
          </div>
        </CollapsibleSection>

        {/* ── 4. Details ── */}
        <CollapsibleSection title="Details" icon={<FaFileAlt className="text-gray-400" size={13} />} defaultOpen={false}>
          <div className="space-y-4">
            <div>
              <FL>Task Description</FL>
              {editable
                ? <textarea
                    rows={6}
                    value={form.description || ''}
                    onChange={e => set('description', e.target.value)}
                    className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-amber-400 focus:outline-none resize-y"
                    placeholder="Task description…"
                  />
                : <div className="text-sm text-gray-700 dark:text-gray-300 whitespace-pre-wrap min-h-[60px] leading-relaxed">
                    {form.description || <span className="text-gray-400 italic">No description</span>}
                  </div>}
            </div>
            <div>
              <FL>Task Obstacles</FL>
              {editable
                ? <textarea
                    rows={4}
                    value={form.custom_task_obstacle || ''}
                    onChange={e => set('custom_task_obstacle', e.target.value)}
                    className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-amber-400 focus:outline-none resize-y"
                    placeholder="Describe obstacles…"
                  />
                : <div className="text-sm text-gray-700 dark:text-gray-300 whitespace-pre-wrap min-h-[48px] leading-relaxed">
                    {form.custom_task_obstacle || <span className="text-gray-400 italic">—</span>}
                  </div>}
            </div>
          </div>
        </CollapsibleSection>

        {/* ── 5. Dependencies ── */}
        <CollapsibleSection title="Dependencies" icon={<FaLink className="text-blue-500" size={13} />} defaultOpen={true}>
          <div className="space-y-4">
            <div>
              <FL>Dependent Tasks</FL>
              <div className="rounded-lg border border-gray-200 dark:border-gray-700 overflow-hidden">
                <div className={`grid ${editable ? 'grid-cols-[40px_1fr_1fr_36px]' : 'grid-cols-[40px_1fr_1fr]'} bg-gray-50 dark:bg-gray-900/50 border-b border-gray-200 dark:border-gray-700`}>
                  <div className="px-3 py-2 text-xs font-medium text-gray-500 uppercase">No.</div>
                  <div className="px-3 py-2 text-xs font-medium text-gray-500 uppercase">Task</div>
                  <div className="px-3 py-2 text-xs font-medium text-gray-500 uppercase">Subject</div>
                  {editable && <div className="py-2 w-9" />}
                </div>
                {dependsOn.length === 0 ? (
                  <div className="py-8 text-center text-sm text-gray-400 dark:text-gray-500 italic">No Data</div>
                ) : (
                  <div className="divide-y divide-gray-100 dark:divide-gray-700">
                    {dependsOn.map((row, idx) => (
                      <div key={idx} className={`grid ${editable ? 'grid-cols-[40px_1fr_1fr_36px]' : 'grid-cols-[40px_1fr_1fr]'} items-center hover:bg-gray-50 dark:hover:bg-gray-700/30`}>
                        <div className="px-3 py-2.5 text-xs text-gray-500 dark:text-gray-400 font-medium">{idx + 1}</div>
                        <div className="px-3 py-1.5">
                          {editable
                            ? <LinkField
                                label="Task"
                                hideLabel
                                doctype="Task"
                                value={row.task || ''}
                                onChange={v => updateDependsOnRow(idx, v)}
                                placeholder="Select task…"
                                compact
                              />
                            : <button
                                onClick={() => row.task && navigate(`/projects/tasks/${row.task}`)}
                                className="text-sm text-indigo-600 dark:text-indigo-400 hover:underline"
                              >
                                {row.task || '-'}
                              </button>}
                        </div>
                        <div className="px-3 py-2.5">
                          <span className="text-sm text-gray-700 dark:text-gray-300">
                            {row.subject || (row.task ? <span className="text-gray-400 italic text-xs">fetching…</span> : '-')}
                          </span>
                        </div>
                        {editable && (
                          <div className="flex justify-center">
                            <button
                              type="button"
                              onClick={() => removeDependsOnRow(idx)}
                              className="p-1.5 text-red-400 hover:text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20 rounded transition-colors"
                              title="Remove row"
                            >
                              <FaTrash size={11} />
                            </button>
                          </div>
                        )}
                      </div>
                    ))}
                  </div>
                )}
                {editable && (
                  <div className="border-t border-gray-200 dark:border-gray-700 px-3 py-2 bg-gray-50 dark:bg-gray-900/30">
                    <button
                      type="button"
                      onClick={addDependsOnRow}
                      className="flex items-center gap-1.5 text-xs text-blue-600 dark:text-blue-400 hover:text-blue-700 font-medium transition-colors"
                    >
                      <FaPlus size={10} /> Add Row
                    </button>
                  </div>
                )}
              </div>
            </div>
            {!isNew && (
              <div>
                <FL>Actual Time In Hours (via Timesheet)</FL>
                <RV>{task?.actual_time ?? 0}</RV>
              </div>
            )}
          </div>
        </CollapsibleSection>

        {/* ── 6. Costing ── */}
        {!isNew && (
          <CollapsibleSection title="Costing" icon={<FaMoneyBillWave className="text-emerald-500" size={13} />} defaultOpen={false}>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-8 gap-y-4">
              <div>
                <FL>Total Costing Amount (via Timesheet)</FL>
                <RV>{fmtCurrency(task?.total_costing_amount)}</RV>
              </div>
              <div>
                <FL>Total Billable Amount (via Timesheet)</FL>
                <RV>{fmtCurrency(task?.total_billing_amount)}</RV>
              </div>
            </div>
          </CollapsibleSection>
        )}

        {/* ── 7. Hierarchy ── */}
        {!isNew && (form.parent_task || dependsOn.length > 0) && (
          <CollapsibleSection title="Task Hierarchy" icon={<FaSitemap className="text-purple-500" size={13} />} defaultOpen={true}>
            <div className="relative">
              <div className="absolute left-[19px] top-0 bottom-0 w-0.5 bg-gradient-to-b from-purple-200 via-indigo-200 to-indigo-100 dark:from-purple-700 dark:via-indigo-700 dark:to-indigo-800" />
              <div className="space-y-2 ml-1">
                {form.parent_task && (
                  <div className="flex items-center gap-3 relative">
                    <div className="w-10 h-10 rounded-full bg-purple-100 dark:bg-purple-900/40 border-2 border-purple-300 dark:border-purple-600 flex items-center justify-center flex-shrink-0 z-10">
                      <svg className="w-4 h-4 text-purple-600 dark:text-purple-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 15l7-7 7 7" />
                      </svg>
                    </div>
                    <button
                      onClick={() => navigate(`/projects/tasks/${form.parent_task}`)}
                      className="flex-1 text-left px-4 py-2.5 rounded-xl bg-purple-50 dark:bg-purple-900/20 border border-purple-200 dark:border-purple-700 hover:bg-purple-100 dark:hover:bg-purple-900/40 transition-colors group"
                    >
                      <div className="flex items-center justify-between">
                        <div>
                          <p className="text-xs font-semibold text-purple-500 dark:text-purple-400 uppercase tracking-wide mb-0.5">Parent Task</p>
                          <p className="text-sm font-medium text-gray-900 dark:text-white group-hover:text-purple-700 dark:group-hover:text-purple-300">
                            {parentTaskInfo?.subject || form.parent_task}
                          </p>
                          <p className="text-xs text-gray-400 dark:text-gray-500 mt-0.5">{form.parent_task}</p>
                        </div>
                        {parentTaskInfo?.status && (
                          <span className="text-xs px-2 py-0.5 rounded-full bg-purple-100 dark:bg-purple-800 text-purple-700 dark:text-purple-300 font-medium">
                            {parentTaskInfo.status}
                          </span>
                        )}
                      </div>
                    </button>
                  </div>
                )}
                <div className="flex items-center gap-3 relative">
                  <div className="w-10 h-10 rounded-full bg-indigo-500 border-2 border-indigo-400 flex items-center justify-center flex-shrink-0 z-10 shadow-md">
                    <FaTasks className="text-white" size={14} />
                  </div>
                  <div className="flex-1 px-4 py-2.5 rounded-xl bg-indigo-50 dark:bg-indigo-900/30 border-2 border-indigo-300 dark:border-indigo-600 shadow-sm">
                    <div className="flex items-center justify-between">
                      <div>
                        <p className="text-xs font-semibold text-indigo-500 dark:text-indigo-400 uppercase tracking-wide mb-0.5">Current Task</p>
                        <p className="text-sm font-semibold text-gray-900 dark:text-white">{form.subject || task?.name}</p>
                        <p className="text-xs text-gray-400 dark:text-gray-500 mt-0.5">{task?.name}</p>
                      </div>
                      <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${
                        form.status === 'Completed' ? 'bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-300' :
                        form.status === 'Working'   ? 'bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300' :
                        form.status === 'Overdue'   ? 'bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-300' :
                        'bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400'
                      }`}>
                        {form.status}
                      </span>
                    </div>
                    {form.progress !== undefined && (
                      <div className="mt-2">
                        <div className="h-1.5 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden">
                          <div className="h-full bg-indigo-500 rounded-full transition-all" style={{ width: `${form.progress}%` }} />
                        </div>
                      </div>
                    )}
                  </div>
                </div>
                {dependsOn.filter(d => d.task).map((dep, i) => (
                  <div key={i} className="flex items-center gap-3 relative">
                    <div className="w-10 h-10 rounded-full bg-teal-100 dark:bg-teal-900/40 border-2 border-teal-300 dark:border-teal-600 flex items-center justify-center flex-shrink-0 z-10">
                      <svg className="w-4 h-4 text-teal-600 dark:text-teal-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                      </svg>
                    </div>
                    <button
                      onClick={() => navigate(`/projects/tasks/${dep.task}`)}
                      className="flex-1 text-left px-4 py-2.5 rounded-xl bg-teal-50 dark:bg-teal-900/20 border border-teal-200 dark:border-teal-700 hover:bg-teal-100 dark:hover:bg-teal-900/40 transition-colors group"
                    >
                      <div>
                        <p className="text-xs font-semibold text-teal-500 dark:text-teal-400 uppercase tracking-wide mb-0.5">Depends on #{i + 1}</p>
                        <p className="text-sm font-medium text-gray-900 dark:text-white group-hover:text-teal-700 dark:group-hover:text-teal-300">
                          {dep.subject || dep.task}
                        </p>
                        {dep.subject && dep.task !== dep.subject && (
                          <p className="text-xs text-gray-400 dark:text-gray-500 mt-0.5">{dep.task}</p>
                        )}
                      </div>
                    </button>
                  </div>
                ))}
              </div>
            </div>
          </CollapsibleSection>
        )}

        {/* ── 8. More Info ── */}
        <CollapsibleSection title="More Info" icon={<FaInfoCircle className="text-gray-400" size={13} />} defaultOpen={false}>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-8 gap-y-4">
            <div>
              <FL>Department</FL>
              {editable
                ? <LinkField label="Department" hideLabel doctype="Department" value={form.department || ''} onChange={v => set('department', v)} placeholder="Select department…" allowQuickCreate />
                : <RV>{form.department || '-'}</RV>}
            </div>
            <div>
              <FL>Company</FL>
              {editable
                ? <LinkField label="Company" hideLabel doctype="Company" value={form.company || ''} onChange={v => set('company', v)} placeholder="Select company…" />
                : <RV>{form.company || '-'}</RV>}
            </div>
            {!isNew && task?.template_task && (
              <div>
                <FL>Template Task</FL>
                <RV>
                  <button onClick={() => navigate(`/projects/tasks/${task.template_task}`)} className="text-indigo-600 dark:text-indigo-400 hover:underline">
                    {task.template_task}
                  </button>
                </RV>
              </div>
            )}
          </div>
        </CollapsibleSection>

        {/* ── Activity Log ── */}
        {!isNew && (
          <ActivityLog
            doctype="Task"
            docname={taskName || ''}
            creationDate={task?.creation}
            createdBy={task?.owner}
            compact={false}
            initialVisible={5}
            collapsible
            startCollapsed
          />
        )}
      </div>
    </div>
  );
};

export default TaskDetail;