import { InputNumber } from 'primereact/inputnumber';
import { Dropdown } from 'primereact/dropdown';
import { Button } from 'primereact/button';
import { NP_CATEGORIES } from '@/core/constants/app.constants';
import type { EntryType } from '../timesheet.types';

interface EntryRow {
  _uid: number;
  entryType: EntryType;
  npCategory?: string;
  otherProjectId?: number;
  epcProjectId?: number;
  canonicalWbsId?: number;
  tealEntryId?: number;
  hours: Record<string, number>;
  remark?: string;
}

interface Props {
  entry: EntryRow;
  projects: { id: number; name: string }[];
  days: string[];
  dayLabels: string[];
  disabled?: boolean;
  onUpdate: (updated: Partial<EntryRow>) => void;
  onRemove: () => void;
}

export default function TimesheetEntryRow({ entry, projects, days, dayLabels, disabled, onUpdate, onRemove }: Props) {
  const rowTotal = Object.values(entry.hours).reduce((a, b) => a + b, 0);

  function setHour(day: string, val: number | null) {
    onUpdate({ hours: { ...entry.hours, [day]: val ?? 0 } });
  }

  return (
    <tr>
      <td>
        {entry.entryType === 'NON_PROJECT' && (
          <Dropdown
            value={entry.npCategory}
            options={NP_CATEGORIES.map((c) => ({ label: c.label, value: c.value }))}
            onChange={(e) => onUpdate({ npCategory: e.value })}
            placeholder="카테고리 선택"
            disabled={disabled}
            style={{ width: '100%' }}
          />
        )}
        {entry.entryType === 'OTHER_PROJECT' && (
          <Dropdown
            value={entry.otherProjectId}
            options={projects.map((p) => ({ label: p.name, value: p.id }))}
            onChange={(e) => onUpdate({ otherProjectId: e.value })}
            placeholder="프로젝트 선택"
            disabled={disabled}
            style={{ width: '100%' }}
          />
        )}
        {entry.entryType === 'EPC' && (
          <Dropdown
            value={entry.epcProjectId}
            options={projects.map((p) => ({ label: p.name, value: p.id }))}
            onChange={(e) => onUpdate({ epcProjectId: e.value })}
            placeholder="프로젝트 선택"
            disabled={disabled}
            style={{ width: '100%' }}
          />
        )}
      </td>
      {days.map((day, i) => (
        <td key={dayLabels[i]} style={{ textAlign: 'center' }}>
          <InputNumber
            value={entry.hours[day] ?? 0}
            onValueChange={(e) => setHour(day, e.value ?? 0)}
            min={0}
            max={16}
            step={0.5}
            disabled={disabled}
            inputStyle={{ width: '60px', textAlign: 'center' }}
            minFractionDigits={1}
            maxFractionDigits={1}
          />
        </td>
      ))}
      <td style={{ textAlign: 'center', fontWeight: 600 }}>{rowTotal.toFixed(1)}</td>
      <td style={{ textAlign: 'center' }}>
        <Button icon="pi pi-times" text rounded severity="danger" size="small" disabled={disabled} onClick={onRemove} />
      </td>
    </tr>
  );
}
