import React, { useState, useEffect, useCallback, useRef, useMemo } from 'react';
import { useParams, useNavigate, useSearchParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import {
  FaArrowLeft, FaSave, FaEdit, FaTimes, FaPlus, FaTrash,
  FaCheckCircle, FaTimesCircle, FaSpinner, FaChevronDown, FaChevronRight,
  FaClock, FaStopwatch, FaStop, FaPencilAlt, FaUser, FaMoneyBillWave, FaFileAlt, FaClipboardList, FaSitemap,
} from 'react-icons/fa';
import { toast, ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { useTimesheetDetails, useProjectMutations } from '../hooks/useProject';
import { FaFileInvoiceDollar, FaPaperPlane } from 'react-icons/fa';
import LinkField from '../components/LinkField';
import type { Timesheet, TimesheetDetail as TimesheetLog } from '../services/projectService';
import ActivityLog from '../components/ActivityLog';
import { DEFAULT_COMPANY, DEFAULT_CURRENCY } from '../constants/orgDefaults';
import projectService from '../services/projectService';

// ─── Helpers ─────────────────────────────────────────────────────────────────

const statusBadge = (s: string) => {
  switch (s?.toLowerCase()) {
    case 'submitted': return 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300';
    case 'cancelled': return 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300';
    default:          return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300';
  }
};

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.5">
    {children}{required && <span className="text-red-500 ml-0.5">*</span>}
  </label>
);

const RV: React.FC<{ children?: React.ReactNode; className?: string }> = ({ children, className }) => (
  <div className={`px-3 py-2.5 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 dark:border-gray-700/50 ${className || ''}`}>
    {children || <span className="text-gray-400 dark:text-gray-600">—</span>}
  </div>
);

const inputCls = 'w-full px-3 py-2.5 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:outline-none focus:ring-2 focus:ring-indigo-400 focus:border-indigo-400 transition-colors';

interface CollapsibleProps {
  title: string;
  icon?: React.ReactNode;
  children: React.ReactNode;
  defaultOpen?: boolean;
}
const CollapsibleSection: React.FC<CollapsibleProps> = ({ title, icon, children, defaultOpen = true }) => {
  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">
      <button
        type="button"
        onClick={() => setOpen(o => !o)}
        className="w-full flex items-center justify-between px-5 py-3.5 hover:bg-gray-50 dark:hover:bg-gray-700/30 transition-colors text-left"
      >
        <div className="flex items-center gap-2 text-sm font-semibold text-gray-700 dark:text-gray-200">
          {icon}
          <span>{title}</span>
        </div>
        {open ? <FaChevronDown className="text-gray-400 text-xs flex-shrink-0" /> : <FaChevronRight className="text-gray-400 text-xs flex-shrink-0" />}
      </button>
      {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>
  );
};

/** Static panel — same chrome as collapsible sections (border, header bar) without toggle */
const TimesheetPanel: React.FC<{ title: string; icon?: React.ReactNode; children: React.ReactNode }> = ({ title, icon, children }) => (
  <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden shadow-sm">
    <div className="px-4 py-2.5 border-b border-gray-100 dark:border-gray-700 bg-gray-50/90 dark:bg-gray-900/40 flex items-center gap-2">
      {icon}
      <h3 className="text-xs font-bold text-gray-600 dark:text-gray-300 uppercase tracking-wider">{title}</h3>
    </div>
    <div className="p-4 sm:p-5">{children}</div>
  </div>
);

// ─── Empty log row ────────────────────────────────────────────────────────────
const emptyLog = (defaults: Partial<TimesheetLog> = {}): Partial<TimesheetLog> => ({
  activity_type: '',
  from_time: undefined,
  to_time: undefined,
  hours: undefined,
  project: defaults.project || '',
  task: defaults.task || '',
  note: '',
  is_billable: 0,
  completed: 0,
});

/** Ensure datetime string has seconds — Frappe requires "YYYY-MM-DD HH:MM:SS" */
const addSeconds = (dt: string) => (dt.length === 16 ? dt + ':00' : dt);

/** Sanitize time logs for Frappe: from_time required; T→space; add seconds. */
const sanitizeLogs = (logs: Partial<TimesheetLog>[]): Partial<TimesheetLog>[] =>
  logs
    .filter(l => l.from_time && l.from_time.trim() !== '')
    .map(l => ({
      ...l,
      from_time: addSeconds(l.from_time!.replace('T', ' ')),
      to_time: l.to_time?.trim() ? addSeconds(l.to_time.replace('T', ' ')) : undefined,
    }));

// ─── Component ────────────────────────────────────────────────────────────────
const TimesheetDetail: React.FC = () => {
  const { t } = useTranslation();
  const { timesheetName } = useParams<{ timesheetName: string }>();
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const isNew = timesheetName === '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);

  // Query params for "create from task/project" context
  const contextProject  = searchParams.get('project')  || '';
  const contextTask     = searchParams.get('task')     || '';
  const contextCustomer = searchParams.get('customer') || '';
  const contextCompany  = searchParams.get('company')  || DEFAULT_COMPANY;

  const { timesheet, loading, error, refetch } = useTimesheetDetails(isNew ? null : (timesheetName || null));
  const { createTimesheet, updateTimesheet, submitTimesheet, loading: saving } = useProjectMutations();
  const [submitting, setSubmitting] = useState(false);
  const [isEditing, setIsEditing] = useState(isNew);
  useEffect(() => { if (startInEditMode) setIsEditing(true); }, [startInEditMode]);

  // ── Expanded row tracking ────────────────────────────────────────────────
  const [expandedRow, setExpandedRow] = useState<number | null>(null);

  // ── Timer ────────────────────────────────────────────────────────────────
  const [timerActive, setTimerActive]     = useState(false);
  const [timerRowIdx, setTimerRowIdx]     = useState<number>(-1);
  const [timerElapsed, setTimerElapsed]   = useState(0);   // seconds
  const timerStartRef                     = useRef<Date | null>(null);
  const timerIntervalRef                  = useRef<ReturnType<typeof setInterval> | null>(null);

  const fmtElapsed = (s: number) => {
    const h = Math.floor(s / 3600).toString().padStart(2, '0');
    const m = Math.floor((s % 3600) / 60).toString().padStart(2, '0');
    const sc = (s % 60).toString().padStart(2, '0');
    return `${h}:${m}:${sc}`;
  };

  const startTimer = () => {
    if (!editable) return;
    // Add a fresh log row with from_time = now
    const now = new Date();
    const fromTime = now.toISOString().replace('T', ' ').slice(0, 19);
    const newLog = emptyLog({ project: form.parent_project || contextProject, task: contextTask });
    newLog.from_time = fromTime;
    setForm(f => ({ ...f, time_logs: [...(f.time_logs || []), newLog] }));
    const newIdx = (form.time_logs || []).length;
    setTimerRowIdx(newIdx);
    setExpandedRow(newIdx);
    timerStartRef.current = now;
    setTimerElapsed(0);
    setTimerActive(true);
    timerIntervalRef.current = setInterval(() => {
      setTimerElapsed(prev => prev + 1);
    }, 1000);
  };

  const stopTimer = () => {
    if (timerIntervalRef.current) clearInterval(timerIntervalRef.current);
    if (timerStartRef.current && timerRowIdx >= 0) {
      const stop = new Date();
      const toTime = stop.toISOString().replace('T', ' ').slice(0, 19);
      const hrs = (stop.getTime() - timerStartRef.current.getTime()) / 3_600_000;
      setForm(f => {
        const logs = [...(f.time_logs || [])];
        if (logs[timerRowIdx]) {
          logs[timerRowIdx] = { ...logs[timerRowIdx], to_time: toTime, hours: parseFloat(hrs.toFixed(4)) };
        }
        return { ...f, time_logs: logs };
      });
    }
    setTimerActive(false);
    setTimerRowIdx(-1);
    timerStartRef.current = null;
  };

  // Clean up interval on unmount
  useEffect(() => () => { if (timerIntervalRef.current) clearInterval(timerIntervalRef.current); }, []);

  // ── Form state ───────────────────────────────────────────────────────────
  const [form, setForm] = useState<Partial<Timesheet>>({
    status:        'Draft',
    currency:      DEFAULT_CURRENCY,
    exchange_rate:  1,
    employee:      '',
    customer:      contextCustomer,
    parent_project: contextProject,
    company:       contextCompany,
    note:          '',
    time_logs:     [emptyLog({ project: contextProject, task: contextTask })],
  });

  const syncForm = useCallback((t: Timesheet) => {
    const headerProject = (t as any).parent_project || t.project || '';
    setForm({
      status:        t.status        || 'Draft',
      currency:      t.currency      || DEFAULT_CURRENCY,
      exchange_rate: t.exchange_rate ?? 1,
      employee:      t.employee      || '',
      customer:      t.customer      || '',
      parent_project: headerProject,
      company:       (t as any).company || (t as any).hospital || DEFAULT_COMPANY,
      note:          t.note          || '',
      time_logs:     t.time_logs?.length ? t.time_logs : [],
    });
  }, []);

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

  // Duplicate: prefill new timesheet from an existing timesheet
  useEffect(() => {
    if (!isNew) return;
    if (!duplicateFrom) return;
    let cancelled = false;
    setIsDuplicating(true);
    projectService
      .getTimesheet(duplicateFrom)
      .then((ts) => {
        if (cancelled) return;
        const copiedLogs: Partial<TimesheetLog>[] = Array.isArray((ts as any).time_logs)
          ? (ts as any).time_logs.map((l: any) => ({
              activity_type: l.activity_type || '',
              from_time: undefined,
              to_time: undefined,
              hours: undefined,
              project: contextProject || l.project || '',
              task: contextTask || l.task || '',
              note: l.note || '',
              is_billable: l.is_billable || 0,
              completed: 0,
            }))
          : [];

        const nextLogs = copiedLogs.length ? copiedLogs : [emptyLog({ project: contextProject, task: contextTask })];
        setForm((prev) => ({
          ...prev,
          status: 'Draft',
          note: (ts as any).note || '',
          // keep context header fields if provided
          parent_project: contextProject || (ts as any).parent_project || (ts as any).project || prev.parent_project,
          customer: contextCustomer || (ts as any).customer || prev.customer,
          company: contextCompany || (ts as any).company || prev.company,
          time_logs: nextLogs,
        }));
        setIsEditing(true);
      })
      .catch(() => {
        // ignore
      })
      .finally(() => {
        if (!cancelled) setIsDuplicating(false);
      });
    return () => { cancelled = true; };
  }, [isNew, duplicateFrom, contextProject, contextTask, contextCustomer, contextCompany]);

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

  // ── Time-log helpers ─────────────────────────────────────────────────────
  const addLog = () => {
    setForm(f => ({
      ...f,
      time_logs: [...(f.time_logs || []), emptyLog({ project: f.parent_project || contextProject, task: contextTask })],
    }));
    // Do NOT auto-expand the new row
  };

  const updateLog = (idx: number, k: keyof TimesheetLog, v: any) =>
    setForm(f => {
      const logs = [...(f.time_logs || [])];
      const updated = { ...logs[idx], [k]: v };

      // Auto-calculate hours when from_time or to_time changes
      if (k === 'from_time' || k === 'to_time') {
        const from = k === 'from_time' ? v : updated.from_time;
        const to   = k === 'to_time'   ? v : updated.to_time;
        if (from && to) {
          const fromMs = new Date(from.replace(' ', 'T')).getTime();
          const toMs   = new Date(to.replace(' ', 'T')).getTime();
          if (toMs > fromMs) {
            const hrs = parseFloat(((toMs - fromMs) / 3_600_000).toFixed(4));
            updated.hours = hrs;
            // Sync billing_hours to hours if they were in sync before
            if (!updated.billing_hours || updated.billing_hours === logs[idx].hours) {
              updated.billing_hours = hrs;
            }
          }
        }
      }

      // When is_billable is toggled on, default billing_hours to hours
      if (k === 'is_billable' && v) {
        if (!updated.billing_hours && updated.hours) {
          updated.billing_hours = updated.hours;
        }
      }

      // Auto-calculate billing_amount = billing_rate × billing_hours
      if (k === 'billing_rate' || k === 'billing_hours') {
        const rate  = k === 'billing_rate'  ? (parseFloat(v) || 0) : (updated.billing_rate  || 0);
        const bhrs  = k === 'billing_hours' ? (parseFloat(v) || 0) : (updated.billing_hours || 0);
        updated.billing_amount = parseFloat((rate * bhrs).toFixed(2));
      }

      // Costing amount = costing_rate × working hours (Hours field), not billing hours
      updated.costing_amount = parseFloat(
        ((updated.costing_rate || 0) * (updated.hours || 0)).toFixed(2),
      );

      logs[idx] = updated;
      return { ...f, time_logs: logs };
    });

  const removeLog = (idx: number) =>
    setForm(f => {
      const logs = [...(f.time_logs || [])];
      logs.splice(idx, 1);
      setExpandedRow(null);
      return { ...f, time_logs: logs };
    });

  // ── Compute total hours from logs ────────────────────────────────────────
  const computedTotal = (form.time_logs || []).reduce((sum, l) => sum + (l.hours || 0), 0);

  // ── Save ─────────────────────────────────────────────────────────────────
  const handleSave = async () => {
    const cleanLogs = sanitizeLogs(form.time_logs || []);
    if (cleanLogs.length === 0) {
      toast.error('At least one time log with a From Time is required.', { icon: <FaTimesCircle /> });
      return;
    }
    const payload: Partial<Timesheet> = {
      status:        form.status,
      currency:      form.currency,
      exchange_rate: form.exchange_rate,
      naming_series: form.naming_series,
      time_logs:     cleanLogs,
      employee:      form.employee     || undefined,
      customer:      form.customer     || undefined,
      company:       form.company      || undefined,
      parent_project: form.parent_project || undefined,
      note:          form.note         || undefined,
    };
    try {
      if (isNew) {
        const created = await createTimesheet(payload);
        toast.success(t('projects.timesheetCreated'), { icon: <FaCheckCircle /> });
        setIsEditing(false);
        navigate(`/projects/timesheets/${created.name}`);
      } else {
        await updateTimesheet(timesheetName!, payload);
        toast.success(t('projects.timesheetUpdated'), { icon: <FaCheckCircle /> });
        setIsEditing(false);
        // Always refetch via GET to ensure company, parent_project, etc. are preserved
        refetch();
      }
    } catch (err) {
      toast.error(err instanceof Error ? err.message : t('common.error'), { icon: <FaTimesCircle /> });
    }
  };

  const handleCancel = () => {
    if (timesheet) syncForm(timesheet);
    setIsEditing(false);
    setExpandedRow(null);
  };

  const handleSubmitTs = async () => {
    if (!timesheetName || isNew) return;
    try {
      setSubmitting(true);
      await submitTimesheet(timesheetName);
      toast.success('Timesheet submitted', { icon: <FaCheckCircle /> });
      refetch();
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'Error submitting', { icon: <FaTimesCircle /> });
    } finally {
      setSubmitting(false);
    }
  };

  const editable = isNew || isEditing;

  if (loading) return (
    <div className="flex items-center justify-center min-h-[400px]">
      <FaSpinner className="animate-spin text-indigo-500 text-3xl" />
    </div>
  );

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

      {/* ── 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-indigo-600 dark:hover:text-indigo-400 transition-colors">
              {t('projects.moduleTitle')}
            </button>
            <span>/</span>
            <button onClick={() => navigate('/projects/timesheets')} className="hover:text-indigo-600 dark:hover:text-indigo-400 transition-colors">
              Timesheets
            </button>
            <span>/</span>
            <span className="text-gray-600 dark:text-gray-300 font-medium">{isNew ? 'New Timesheet' : timesheetName}</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/timesheets')}
              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-indigo-600 flex items-center justify-center flex-shrink-0 shadow-sm">
                  <FaClock className="text-white text-sm" />
                </div>
                <div>
                  <h1 className="text-xl font-bold text-gray-900 dark:text-white leading-tight">
                    {isNew ? 'New Timesheet' : timesheetName}
                  </h1>
                  {!isNew && (
                    <p className="text-xs text-gray-400 dark:text-gray-500 mt-0.5">Series: TS-.YYYY.-</p>
                  )}
                </div>
                <span className={`inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-semibold ${
                  timesheet?.docstatus === 1 ? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300' :
                  timesheet?.docstatus === 2 ? 'bg-red-100 text-red-700' :
                  statusBadge(form.status || 'Draft')
                }`}>
                  <FaClock size={9} />
                  {timesheet?.docstatus === 1 ? 'Submitted' : timesheet?.docstatus === 2 ? 'Cancelled' : (form.status || 'Draft')}
                </span>
              </div>
            </div>
          </div>

          <div className="flex items-center gap-2 flex-wrap">
            {/* Create Sales Invoice — shown when submitted */}
            {!isNew && !isEditing && timesheet?.docstatus === 1 && (
              <button
                onClick={() => {
                  const p = new URLSearchParams({ customer: form.customer || '' });
                  if (form.company) p.set('company', String(form.company));
                  if (form.parent_project) p.set('project', String(form.parent_project));
                  navigate(`/invoices/new?${p.toString()}`);
                }}
                className="flex items-center gap-2 px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 text-sm font-medium"
              >
                <FaFileInvoiceDollar size={13} /> Create Sales Invoice
              </button>
            )}
            {/* Submit — shown when saved as draft */}
            {!isNew && !isEditing && timesheet?.docstatus === 0 && (
              <button
                onClick={handleSubmitTs}
                disabled={submitting}
                className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 text-sm font-medium"
              >
                {submitting ? <FaSpinner className="animate-spin" /> : <FaPaperPlane size={12} />}
                Submit
              </button>
            )}
            {/* Start / Stop Timer */}
            {editable && (
              timerActive ? (
                <button
                  type="button"
                  onClick={stopTimer}
                  className="flex items-center gap-2 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 text-sm font-medium shadow-sm"
                >
                  <FaStop size={11} />
                  <span className="font-mono tracking-widest">{fmtElapsed(timerElapsed)}</span>
                  Stop Timer
                </button>
              ) : (
                <button
                  type="button"
                  onClick={startTimer}
                  className="flex items-center gap-2 px-4 py-2 bg-gray-800 dark:bg-gray-700 text-white rounded-lg hover:bg-gray-900 dark:hover:bg-gray-600 text-sm font-medium"
                >
                  <FaStopwatch /> Start Timer
                </button>
              )
            )}
            {!isNew && !isEditing && (
              <button
                onClick={() => setIsEditing(true)}
                className="flex items-center gap-2 px-4 py-2 border border-indigo-500 text-indigo-600 dark:text-indigo-400 rounded-lg hover:bg-indigo-50 dark:hover:bg-indigo-900/20 text-sm transition-colors"
              >
                <FaEdit /> {t('common.edit')}
              </button>
            )}
            {editable && (
              <>
                <button
                  onClick={handleSave}
                  disabled={saving}
                  className="flex items-center gap-2 px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 disabled:opacity-50 text-sm font-medium shadow-sm"
                >
                  {saving ? <FaSpinner className="animate-spin" /> : <FaSave />}
                  {saving ? t('common.saving') : t('common.save')}
                </button>
                {!isNew && (
                  <button
                    onClick={handleCancel}
                    className="px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-gray-600 dark:text-gray-400 text-sm"
                  >
                    <FaTimes />
                  </button>
                )}
              </>
            )}
          </div>
        </div>
        </div>
      </div>

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

        {error && !isNew && (
          <div className="p-3 bg-red-50 dark:bg-red-900/20 rounded-lg text-red-700 dark:text-red-300 text-sm">
            {error}
          </div>
        )}

        {!isNew && timesheet && (
          <TimesheetPanel title="Summary" icon={<FaClock className="text-indigo-500 flex-shrink-0" size={13} />}>
            <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
              {[
                { label: 'Total Hours',     value: `${timesheet.total_hours ?? 0} hrs` },
                { label: 'Billable Hours',  value: `${timesheet.total_billable_hours ?? 0} hrs` },
                { label: 'Billable Amount', value: `${timesheet.currency || DEFAULT_CURRENCY} ${timesheet.total_billable_amount ?? 0}` },
                { label: 'Costing Amount',  value: `${timesheet.currency || DEFAULT_CURRENCY} ${timesheet.total_costing_amount ?? 0}` },
              ].map(({ label, value }) => (
                <div
                  key={label}
                  className="rounded-lg border border-gray-200/80 dark:border-gray-600/80 bg-gray-50/80 dark:bg-gray-900/40 px-3 py-2.5 min-h-[72px] flex flex-col justify-center"
                >
                  <p className="text-[10px] font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1">{label}</p>
                  <p className="text-sm font-semibold text-gray-900 dark:text-white tabular-nums leading-snug">{value}</p>
                </div>
              ))}
            </div>
          </TimesheetPanel>
        )}

        <TimesheetPanel title="Document" icon={<FaClipboardList className="text-indigo-500 flex-shrink-0" size={13} />}>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-8 gap-y-4">
            <div className="min-w-0">
              <FL>Series</FL>
              <RV>TS-.YYYY.-</RV>
            </div>
            <div className="min-w-0">
              <FL>Status</FL>
              {editable ? (
                <select
                  value={form.status || 'Draft'}
                  onChange={e => set('status', e.target.value)}
                  className={inputCls}
                >
                  <option value="Draft">Draft</option>
                  <option value="Submitted">Submitted</option>
                  <option value="Cancelled">Cancelled</option>
                </select>
              ) : (
                <RV>
                  <span className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-md text-xs font-semibold ${statusBadge(form.status || 'Draft')}`}>
                    {form.status || 'Draft'}
                  </span>
                </RV>
              )}
            </div>
          </div>
        </TimesheetPanel>

        <TimesheetPanel title="Organization" icon={<FaSitemap className="text-indigo-500 flex-shrink-0" size={13} />}>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-8 gap-y-4">
            <div className="min-w-0">
              <FL>Hospital</FL>
              {editable
                ? <LinkField
                    label="Hospital"
                    hideLabel
                    doctype="Company"
                    value={form.company || ''}
                    onChange={v => set('company', v)}
                    placeholder="Select hospital / company…"
                  />
                : <RV>{form.company}</RV>}
            </div>
            <div className="min-w-0">
              <FL>Project</FL>
              {editable
                ? <LinkField
                    label="Project"
                    hideLabel
                    doctype="Project"
                    value={form.parent_project || ''}
                    onChange={v => set('parent_project', v)}
                    placeholder="Select project…"
                  />
                : <RV>
                    {form.parent_project
                      ? <button
                          type="button"
                          onClick={() => navigate(`/projects/list/${form.parent_project}`)}
                          className="text-indigo-600 dark:text-indigo-400 hover:underline font-medium"
                        >
                          {form.parent_project}
                        </button>
                      : null}
                  </RV>}
            </div>
          </div>
        </TimesheetPanel>

        <TimesheetPanel title="Customer & currency" icon={<FaMoneyBillWave className="text-indigo-500 flex-shrink-0" size={13} />}>
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-x-8 gap-y-4">
            <div className="min-w-0 sm:col-span-2 lg:col-span-1">
              <FL>Customer</FL>
              {editable
                ? <LinkField
                    label="Customer"
                    hideLabel
                    doctype="Customer"
                    value={form.customer || ''}
                    onChange={v => set('customer', v)}
                    placeholder="Select customer…"
                  />
                : <RV>{form.customer}</RV>}
            </div>
            <div className="min-w-0">
              <FL>Currency</FL>
              <RV>{form.currency || DEFAULT_CURRENCY}</RV>
            </div>
            <div className="min-w-0">
              <FL>Exchange rate</FL>
              <RV>{form.exchange_rate ?? 1}</RV>
            </div>
          </div>
        </TimesheetPanel>

        {/* ── Employee Detail ──────────────────────────────────────────── */}
        <CollapsibleSection title="Employee Detail" icon={<FaUser className="text-indigo-500" size={13} />}>
          <div className="max-w-sm">
            <FL>Employee</FL>
            {editable
              ? <LinkField
                  label="Employee"
                  hideLabel
                  doctype="Employee"
                  value={form.employee || ''}
                  onChange={v => set('employee', v)}
                  placeholder="Select employee…"
                  filters={{ status: 'Active' }}
                  allowQuickCreate
                />
              : <RV>{form.employee}</RV>}
          </div>
        </CollapsibleSection>

        {/* ── Time Sheets child table ──────────────────────────────────── */}
        <CollapsibleSection title="Time Sheets" icon={<FaClock className="text-indigo-500" size={13} />} defaultOpen>
          {/* Table */}
          <div className="overflow-x-auto rounded-lg border border-gray-200 dark:border-gray-700 mb-3">

            {/* Header row — cols: No | Activity Type | From Time | To Time | Hrs | Project | Billable | (del) */}
            <div className={`grid ${editable
              ? 'grid-cols-[40px_minmax(130px,1fr)_155px_155px_70px_minmax(110px,1fr)_58px_36px]'
              : 'grid-cols-[40px_minmax(130px,1fr)_155px_155px_70px_minmax(110px,1fr)_58px]'}
              bg-gray-50 dark:bg-gray-900/50 border-b border-gray-200 dark:border-gray-700 text-xs font-medium text-gray-500 dark:text-gray-400 uppercase`}>
              <div className="px-3 py-2">No.</div>
              <div className="px-3 py-2">Activity Type</div>
              <div className="px-3 py-2">From Time <span className="text-red-400">*</span></div>
              <div className="px-3 py-2">To Time</div>
              <div className="px-3 py-2">Hrs</div>
              <div className="px-3 py-2">Project</div>
              <div className="px-3 py-2 text-center">Billable</div>
              <div className="py-2" />
              {editable && <div className="py-2" />}
            </div>

            {(form.time_logs || []).length === 0 ? (
              <div className="py-10 text-center text-sm text-gray-400 dark:text-gray-500 italic">
                {editable ? 'Click "Add Row" below to add time entries' : 'No time logs'}
              </div>
            ) : (
              <div className="divide-y divide-gray-100 dark:divide-gray-700">
                {(form.time_logs || []).map((log, idx) => (
                  <React.Fragment key={idx}>
                    {/* Main row — highlighted when timer is running on this row */}
                    <div
                      className={`grid ${editable
                        ? 'grid-cols-[40px_minmax(130px,1fr)_155px_155px_70px_minmax(110px,1fr)_58px_32px_36px]'
                        : 'grid-cols-[40px_minmax(130px,1fr)_155px_155px_70px_minmax(110px,1fr)_58px_32px]'}
                        items-center hover:bg-gray-50 dark:hover:bg-gray-700/20
                        ${expandedRow === idx ? 'bg-indigo-50 dark:bg-indigo-900/10' : ''}
                        ${timerActive && timerRowIdx === idx ? 'bg-red-50 dark:bg-red-900/10 border-l-2 border-red-400' : ''}`}
                    >
                      <div className="px-3 py-2.5 text-xs text-gray-500 font-medium">{idx + 1}</div>

                      {/* Activity Type */}
                      <div className="px-2 py-1.5" onClick={e => e.stopPropagation()}>
                        {editable
                          ? <LinkField
                              label="Activity Type"
                              hideLabel
                              doctype="Activity Type"
                              value={log.activity_type || ''}
                              onChange={v => updateLog(idx, 'activity_type', v)}
                              placeholder="Activity…"
                              allowQuickCreate
                              compact
                            />
                          : <span className="text-sm text-gray-800 dark:text-gray-200">{log.activity_type || '-'}</span>}
                      </div>

                      {/* From Time (required) */}
                      <div className="px-2 py-1.5" onClick={e => e.stopPropagation()}>
                        {editable
                          ? <input
                              type="datetime-local"
                              value={log.from_time ? log.from_time.replace(' ', 'T').slice(0, 16) : ''}
                              onChange={e => updateLog(idx, 'from_time', e.target.value || undefined)}
                              required
                              className={`text-xs border rounded px-2 py-1.5 w-full focus:outline-none focus:ring-1 focus:ring-indigo-400 ${
                                !log.from_time
                                  ? 'border-red-300 bg-red-50 dark:bg-red-900/20 dark:border-red-600'
                                  : 'border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700'
                              } text-gray-900 dark:text-white`}
                            />
                          : <span className="text-xs text-gray-700 dark:text-gray-300">{log.from_time || '-'}</span>}
                      </div>

                      {/* To Time — auto-calculates Hrs when both times are set */}
                      <div className="px-2 py-1.5" onClick={e => e.stopPropagation()}>
                        {editable
                          ? <input
                              type="datetime-local"
                              value={log.to_time ? log.to_time.replace(' ', 'T').slice(0, 16) : ''}
                              onChange={e => updateLog(idx, 'to_time', e.target.value || undefined)}
                              className="text-xs border border-gray-300 dark:border-gray-600 rounded px-2 py-1.5 w-full bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:outline-none focus:ring-1 focus:ring-indigo-400"
                            />
                          : <span className="text-xs text-gray-700 dark:text-gray-300">{log.to_time || '-'}</span>}
                      </div>

                      {/* Hrs — auto-filled; can also be manually set */}
                      <div className="px-2 py-1.5" onClick={e => e.stopPropagation()}>
                        {editable
                          ? <input
                              type="number" min={0} step={0.25}
                              value={log.hours ?? ''}
                              onChange={e => updateLog(idx, 'hours', parseFloat(e.target.value) || undefined)}
                              placeholder="0"
                              className="text-xs border border-gray-300 dark:border-gray-600 rounded px-2 py-1.5 w-full bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:outline-none focus:ring-1 focus:ring-indigo-400"
                            />
                          : <span className="text-sm font-medium text-gray-800 dark:text-gray-200">{(log.hours ?? 0).toFixed(3)}</span>}
                      </div>

                      {/* Project */}
                      <div className="px-2 py-1.5" onClick={e => e.stopPropagation()}>
                        {editable
                          ? <LinkField
                              label="Project"
                              hideLabel
                              doctype="Project"
                              value={log.project || ''}
                              onChange={v => updateLog(idx, 'project', v)}
                              placeholder="Project…"
                              compact
                            />
                          : <span className="text-sm text-gray-800 dark:text-gray-200">{log.project || '-'}</span>}
                      </div>

                      {/* Is Billable */}
                      <div className="px-3 py-2.5 flex justify-center" onClick={e => e.stopPropagation()}>
                        <input
                          type="checkbox"
                          checked={!!log.is_billable}
                          onChange={e => updateLog(idx, 'is_billable', e.target.checked ? 1 : 0)}
                          disabled={!editable}
                          className="w-4 h-4 text-green-600 rounded cursor-pointer"
                        />
                      </div>

                      {/* Expand / edit details */}
                      <div className="flex justify-center" onClick={e => e.stopPropagation()}>
                        <button
                          type="button"
                          onClick={() => setExpandedRow(expandedRow === idx ? null : idx)}
                          className={`p-1.5 rounded transition-colors ${expandedRow === idx ? 'text-indigo-600 bg-indigo-100 dark:bg-indigo-900/30' : 'text-gray-400 hover:text-indigo-600 hover:bg-indigo-50 dark:hover:bg-indigo-900/20'}`}
                          title="Edit row details"
                        >
                          <FaPencilAlt size={11} />
                        </button>
                      </div>

                      {/* Delete */}
                      {editable && (
                        <div className="flex justify-center" onClick={e => e.stopPropagation()}>
                          <button
                            type="button"
                            onClick={() => removeLog(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>

                    {/* ── Expanded row detail panel ── */}
                    {expandedRow === idx && (
                      <div className="border-t border-indigo-100 dark:border-indigo-800/40 bg-indigo-50/60 dark:bg-indigo-900/10 px-4 py-4 mx-0">
                        <div className="flex items-center justify-between mb-3">
                          <span className="text-xs font-semibold text-indigo-700 dark:text-indigo-400 uppercase tracking-wide">
                            Editing Row #{idx + 1}
                          </span>
                          <button
                            type="button"
                            onClick={() => setExpandedRow(null)}
                            className="text-xs text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 px-2 py-0.5 rounded hover:bg-gray-200 dark:hover:bg-gray-700"
                          >
                            ✕ Close
                          </button>
                        </div>

                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-3">
                          {/* Activity Type */}
                          <div>
                            <FL>Activity Type</FL>
                            {editable
                              ? <LinkField label="Activity Type" hideLabel doctype="Activity Type" value={log.activity_type || ''} onChange={v => updateLog(idx, 'activity_type', v)} placeholder="Select activity…" allowQuickCreate />
                              : <RV>{log.activity_type || '-'}</RV>}
                          </div>

                          {/* Hrs (read-only computed) */}
                          <div>
                            <FL>Hours</FL>
                            <RV>{(log.hours ?? 0).toFixed(3)}</RV>
                          </div>

                          {/* From Time */}
                          <div>
                            <FL required>From Time</FL>
                            {editable
                              ? <input type="datetime-local" value={log.from_time ? log.from_time.replace(' ', 'T').slice(0, 16) : ''} onChange={e => updateLog(idx, 'from_time', e.target.value || undefined)} className="w-full text-sm border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2 bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-indigo-400 focus:outline-none" />
                              : <RV>{log.from_time || '-'}</RV>}
                          </div>

                          {/* To Time */}
                          <div>
                            <FL>To Time</FL>
                            {editable
                              ? <input type="datetime-local" value={log.to_time ? log.to_time.replace(' ', 'T').slice(0, 16) : ''} onChange={e => updateLog(idx, 'to_time', e.target.value || undefined)} className="w-full text-sm border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2 bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-indigo-400 focus:outline-none" />
                              : <RV>{log.to_time || '-'}</RV>}
                          </div>

                          {/* Description (note) — full width */}
                          <div className="sm:col-span-2">
                            <FL>Description</FL>
                            {editable
                              ? <textarea rows={2} value={log.note || ''} onChange={e => updateLog(idx, 'note', e.target.value)} placeholder="Add notes…" className="w-full text-sm border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2 bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-indigo-400 focus:outline-none resize-none" />
                              : <RV>{log.note || '-'}</RV>}
                          </div>

                          {/* Project */}
                          <div>
                            <FL>Project</FL>
                            {editable
                              ? <LinkField label="Project" hideLabel doctype="Project" value={log.project || ''} onChange={v => updateLog(idx, 'project', v)} placeholder="Select project…" />
                              : <RV>{log.project || '-'}</RV>}
                          </div>

                          {/* Completed */}
                          <div className="flex items-center gap-3 pt-5">
                            <input type="checkbox" id={`completed-${idx}`} checked={!!log.completed} onChange={e => updateLog(idx, 'completed', e.target.checked ? 1 : 0)} disabled={!editable} className="w-4 h-4 text-green-600 rounded" />
                            <label htmlFor={`completed-${idx}`} className="text-sm font-medium text-gray-700 dark:text-gray-300 cursor-pointer">Completed</label>
                          </div>

                          {/* Is Billable */}
                          <div className="flex items-center gap-3">
                            <input type="checkbox" id={`billable-${idx}`} checked={!!log.is_billable} onChange={e => updateLog(idx, 'is_billable', e.target.checked ? 1 : 0)} disabled={!editable} className="w-4 h-4 text-green-600 rounded" />
                            <label htmlFor={`billable-${idx}`} className="text-sm font-medium text-gray-700 dark:text-gray-300 cursor-pointer">Is Billable</label>
                          </div>

                          {/* Billing Hours */}
                          <div>
                            <FL>Billing Hours</FL>
                            {editable
                              ? <input type="number" min={0} step={0.01} value={log.billing_hours ?? ''} onChange={e => updateLog(idx, 'billing_hours', parseFloat(e.target.value) || undefined)} placeholder="0" className="w-full text-sm border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2 bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-indigo-400 focus:outline-none" />
                              : <RV>{log.billing_hours ?? '-'}</RV>}
                          </div>
                        </div>

                        {/* Billing/Costing amounts — always in 2-col grid */}
                        <div className="grid grid-cols-2 gap-x-6 gap-y-3 mt-3 pt-3 border-t border-indigo-100 dark:border-indigo-800/40">
                          <div>
                            <FL>Billing Rate ({form.currency || DEFAULT_CURRENCY})</FL>
                            {editable
                              ? <input type="number" min={0} step={0.01} value={log.billing_rate ?? ''} onChange={e => updateLog(idx, 'billing_rate', parseFloat(e.target.value) || undefined)} placeholder="0.00" className="w-full text-sm border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2 bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-indigo-400 focus:outline-none" />
                              : <RV>{log.billing_rate != null ? `${form.currency || DEFAULT_CURRENCY} ${log.billing_rate.toFixed(2)}` : '-'}</RV>}
                          </div>
                          <div>
                            <FL>Billing Amount ({form.currency || DEFAULT_CURRENCY})</FL>
                            <RV className="font-semibold text-green-700 dark:text-green-400">
                              {log.billing_amount != null ? `${form.currency || DEFAULT_CURRENCY} ${log.billing_amount.toFixed(2)}` : '-'}
                            </RV>
                          </div>
                          <div>
                            <FL>Costing Rate ({form.currency || DEFAULT_CURRENCY})</FL>
                            {editable
                              ? <input type="number" min={0} step={0.01} value={log.costing_rate ?? ''} onChange={e => updateLog(idx, 'costing_rate', parseFloat(e.target.value) || undefined)} placeholder="0.00" className="w-full text-sm border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2 bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-indigo-400 focus:outline-none" />
                              : <RV>{log.costing_rate != null ? `${form.currency || DEFAULT_CURRENCY} ${log.costing_rate.toFixed(2)}` : '-'}</RV>}
                          </div>
                          <div>
                            <FL>Costing Amount ({form.currency || DEFAULT_CURRENCY})</FL>
                            <RV>{log.costing_amount != null ? `${form.currency || DEFAULT_CURRENCY} ${log.costing_amount.toFixed(2)}` : '-'}</RV>
                          </div>
                        </div>
                      </div>
                    )}

                    {/* Read-mode: show completed status if set */}
                    {!editable && !!log.completed && (
                      <div className="bg-gray-50 dark:bg-gray-900/30 px-6 pb-1 text-xs text-green-600 dark:text-green-400">
                        ✓ Completed
                      </div>
                    )}
                  </React.Fragment>
                ))}
              </div>
            )}
          </div>

          {/* Add Row */}
          {editable && (
            <button
              type="button"
              onClick={addLog}
              className="flex items-center gap-1.5 px-3 py-1.5 text-sm text-indigo-700 dark:text-indigo-400 border border-indigo-300 dark:border-indigo-700 rounded-lg hover:bg-indigo-50 dark:hover:bg-indigo-900/20 transition-colors"
            >
              <FaPlus size={10} /> Add Row
            </button>
          )}

          {/* Total Working Hours */}
          <div className="mt-4 flex items-center justify-between border-t border-gray-100 dark:border-gray-700 pt-3">
            <span className="text-sm font-semibold text-gray-700 dark:text-gray-300">
              Total Working Hours
            </span>
            <span className="text-sm font-bold text-gray-900 dark:text-white bg-gray-100 dark:bg-gray-700 px-3 py-1 rounded-lg">
              {isNew ? computedTotal.toFixed(3) : (timesheet?.total_hours ?? computedTotal).toFixed ? (timesheet?.total_hours ?? computedTotal).toFixed(3) : '0.000'}
            </span>
          </div>
        </CollapsibleSection>

        {/* ── Billing Details ──────────────────────────────────────────── */}
        <CollapsibleSection title="Billing Details" icon={<FaMoneyBillWave className="text-indigo-500" size={13} />} defaultOpen={false}>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            {(() => {
              const logs = form.time_logs || [];
              const currency = form.currency || DEFAULT_CURRENCY;
              const billableHrs = logs.filter(l => l.is_billable).reduce((s, l) => s + (l.billing_hours || l.hours || 0), 0);
              const billableAmt = logs.filter(l => l.is_billable).reduce((s, l) => s + (l.billing_amount || 0), 0);
              const costingAmt  = logs.reduce((s, l) => s + (l.costing_amount || 0), 0);
              const serverBillableHrs = timesheet?.total_billable_hours;
              const serverBillableAmt = timesheet?.total_billable_amount;
              const serverCostingAmt  = timesheet?.total_costing_amount;
              return [
                { label: 'Total Billable Hours',  value: `${(serverBillableHrs ?? billableHrs).toFixed ? (serverBillableHrs ?? billableHrs).toFixed(3) : billableHrs.toFixed(3)} hrs` },
                { label: 'Total Billable Amount', value: `${currency} ${(serverBillableAmt ?? billableAmt).toFixed(2)}` },
                { label: 'Total Costing Amount',  value: `${currency} ${(serverCostingAmt  ?? costingAmt).toFixed(2)}` },
              ].map(({ label, value }) => (
                <div key={label}>
                  <FL>{label}</FL>
                  <RV>{value}</RV>
                </div>
              ));
            })()}
          </div>
        </CollapsibleSection>

        {/* ── Note ────────────────────────────────────────────────────── */}
        <CollapsibleSection title="Note" icon={<FaFileAlt className="text-gray-400" size={13} />} defaultOpen={false}>
          {editable
            ? <textarea
                value={form.note || ''}
                onChange={e => set('note', e.target.value)}
                rows={4}
                placeholder="Add notes for this timesheet…"
                className={`${inputCls} resize-y`}
              />
            : <RV>{form.note}</RV>}
        </CollapsibleSection>

        {/* ── Meta ────────────────────────────────────────────────────── */}
        {!isNew && timesheet && (
          <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 shadow-sm py-4 px-5 grid grid-cols-2 sm:grid-cols-3 gap-3 text-xs text-gray-400 dark:text-gray-500">
            <div><span className="font-medium block text-gray-500 dark:text-gray-400">Created By</span>{timesheet.owner || '-'}</div>
            <div><span className="font-medium block text-gray-500 dark:text-gray-400">Created</span>{timesheet.creation ? new Date(timesheet.creation).toLocaleString() : '-'}</div>
            <div><span className="font-medium block text-gray-500 dark:text-gray-400">Modified</span>{timesheet.modified ? new Date(timesheet.modified).toLocaleString() : '-'}</div>
          </div>
        )}

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

export default TimesheetDetail;
