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

export default function ApprovalHistoryView() {
  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);

  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);

    approvalService.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}>
        <Column field="requesterName" header="요청자" sortable />
        <Column field="projectName" header="프로젝트" sortable />
        <Column field="weekStartDate" header="주 시작일" sortable />
        <Column field="totalHours" header="시수" body={(row) => `${row.totalHours}h`} />
        <Column field="status" header="상태" body={(row) => {
          const s = TIMESHEET_STATUS[row.status as string];
          return <Tag value={s?.label ?? (row.status as string)} severity={(s?.severity ?? 'secondary') as 'success' | 'info' | 'warning' | 'danger' | 'secondary'} />;
        }} />
        <Column field="approvedAt" header="처리일" sortable />
      </BaseCrudTable>
    </div>
  );
}
