import { useState, useEffect } from 'react';
import { Column } from 'primereact/column';
import { Button } from 'primereact/button';
import { Tag } from 'primereact/tag';
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 type { Approval } from '../approval.types';
import { toArray } from '@/core/api/utils';

export default function ApprovalPendingView() {
  const [loading, setLoading] = useState(false);
  const [approvals, setApprovals] = useState<Approval[]>([]);
  const [selected, setSelected] = useState<Approval[]>([]);

  function load() {
    setLoading(true);
    approvalService.getPending()
      .then(({ data }) => setApprovals(toArray<Approval>(data)))
      .catch(() => setApprovals([]))
      .finally(() => setLoading(false));
  }

  useEffect(() => { load(); }, []);

  async function handleApprove(id: number) {
    await approvalService.approve(id);
    load();
  }

  async function handleReject(id: number) {
    await approvalService.reject(id);
    load();
  }

  async function batchApprove() {
    if (selected.length === 0) return;
    await approvalService.batchApprove(selected.map((s) => s.id));
    setSelected([]);
    load();
  }

  return (
    <div>
      <BasePageHeader title="결재 대기" />
      <BaseCrudTable
        value={approvals}
        loading={loading}
        selectionMode="checkbox"
        toolbarLeft={
          <Button label="일괄 승인" icon="pi pi-check-circle" size="small" disabled={selected.length === 0} onClick={batchApprove} />
        }
      >
        <Column selectionMode="multiple" headerStyle={{ width: '3em' }} />
        <Column field="requesterName" header="요청자" sortable />
        <Column field="projectName" header="프로젝트" sortable />
        <Column field="weekStartDate" header="주 시작일" sortable />
        <Column field="totalHours" header="시수" body={(row) => `${row.totalHours}h`} sortable />
        <Column field="status" header="상태" body={(row) => {
          const s = TIMESHEET_STATUS[row.status];
          return <Tag value={s?.label ?? row.status} severity={(s?.severity ?? 'secondary') as 'success' | 'info' | 'warning' | 'danger' | 'secondary'} />;
        }} />
        <Column header="액션" body={(row) => (
          <div style={{ display: 'flex', gap: '0.25rem' }}>
            <Button icon="pi pi-check" severity="success" text size="small" onClick={() => handleApprove(row.id)} />
            <Button icon="pi pi-times" severity="danger" text size="small" onClick={() => handleReject(row.id)} />
          </div>
        )} />
      </BaseCrudTable>
    </div>
  );
}
