import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Column } from 'primereact/column';
import { Tag } from 'primereact/tag';
import { Dropdown } from 'primereact/dropdown';
import { Calendar } from 'primereact/calendar';
import BaseCrudTable from '@/core/components/BaseCrudTable';
import BasePageHeader from '@/core/components/BasePageHeader';
import { timesheetService } from '../timesheet.service';
import { TIMESHEET_STATUS } from '@/core/constants/app.constants';
import { toArray } from '@/core/api/utils';

export default function TimesheetHistoryView() {
  const [loading, setLoading] = useState(false);
  const [history, setHistory] = useState<Record<string, unknown>[]>([]);
  const [statusFilter, setStatusFilter] = useState<string | null>(null);
  const [dateFrom, setDateFrom] = useState<Date | null>(null);
  const [dateTo, setDateTo] = useState<Date | null>(null);
  const navigate = useNavigate();

  useEffect(() => {
    setLoading(true);
    const params: Record<string, unknown> = {};
    if (statusFilter) params.status = statusFilter;
    if (dateFrom) params.from = dateFrom.toISOString().slice(0, 10);
    if (dateTo) params.to = dateTo.toISOString().slice(0, 10);

    timesheetService.getHistory(params)
      .then(({ data }) => setHistory(toArray<Record<string, unknown>>(data)))
      .catch(() => setHistory([]))
      .finally(() => setLoading(false));
  }, [statusFilter, dateFrom, dateTo]);

  const statusOptions = Object.entries(TIMESHEET_STATUS).map(([key, val]) => ({ label: val.label, value: key }));

  return (
    <div>
      <BasePageHeader title="시수 이력" />
      <div style={{ display: 'flex', gap: '0.5rem', marginBottom: '1rem', flexWrap: 'wrap' }}>
        <Calendar value={dateFrom} onChange={(e) => setDateFrom(e.value as Date)} placeholder="시작일" dateFormat="yy-mm-dd" />
        <Calendar value={dateTo} onChange={(e) => setDateTo(e.value as Date)} placeholder="종료일" dateFormat="yy-mm-dd" />
        <Dropdown value={statusFilter} options={statusOptions} onChange={(e) => setStatusFilter(e.value)} placeholder="상태" showClear />
      </div>
      <BaseCrudTable value={history} loading={loading} rowsPerPage={10}>
        <Column field="weekStartDate" header="시작일" sortable />
        <Column field="weekEndDate" header="종료일" sortable />
        <Column field="totalHours" header="총 시수" body={(row) => `${row.totalHours}h`} sortable />
        <Column field="status" header="상태" body={(row) => {
          const s = TIMESHEET_STATUS[row.status as string];
          return <Tag value={s?.label ?? row.status} severity={(s?.severity ?? 'secondary') as 'success' | 'info' | 'warning' | 'danger' | 'secondary'} />;
        }} />
        <Column field="submittedAt" header="제출일" sortable />
        <Column header="" body={(row) => <a onClick={() => navigate(`/timesheets?week=${row.weekStartDate}`)} style={{ cursor: 'pointer', color: 'var(--p-primary-color)' }}>상세</a>} />
      </BaseCrudTable>
    </div>
  );
}
