import { useState, useEffect } from 'react';
import { TabView, TabPanel } from 'primereact/tabview';
import { Button } from 'primereact/button';
import { Column } from 'primereact/column';
import { Tag } from 'primereact/tag';
import { Card } from 'primereact/card';
import { InputNumber } from 'primereact/inputnumber';
import BaseCrudTable from '@/core/components/BaseCrudTable';
import BasePageHeader from '@/core/components/BasePageHeader';
import OverheadTypeDialog from '../components/OverheadTypeDialog';
import { settingsService } from '../settings.service';
import type { OverheadType, WorkRule } from '../settings.types';

export default function SettingsView() {
  const [overheadTypes, setOverheadTypes] = useState<OverheadType[]>([]);
  const [workRule, setWorkRule] = useState<WorkRule>({ id: 0, minDailyHours: 8, maxWeeklyHours: 52 });
  const [loading, setLoading] = useState(false);
  const [dialogVisible, setDialogVisible] = useState(false);
  const [editOt, setEditOt] = useState<OverheadType | null>(null);
  const [savingRule, setSavingRule] = useState(false);

  function loadOverheadTypes() {
    settingsService.getOverheadTypes()
      .then(({ data }) => setOverheadTypes(Array.isArray(data) ? data : (data as { items?: OverheadType[] }).items ?? []))
      .catch(() => setOverheadTypes([]));
  }

  function loadWorkRules() {
    settingsService.getWorkRules()
      .then(({ data }) => {
        const rules = Array.isArray(data) ? data : [data];
        if (rules.length > 0) setWorkRule(rules[0] as WorkRule);
      })
      .catch(() => {});
  }

  useEffect(() => {
    setLoading(true);
    Promise.all([loadOverheadTypes(), loadWorkRules()]).finally(() => setLoading(false));
  }, []);

  function openCreate() { setEditOt(null); setDialogVisible(true); }
  function openEdit(ot: OverheadType) { setEditOt(ot); setDialogVisible(true); }

  async function onSaveOt(data: Partial<OverheadType>) {
    if (editOt) {
      await settingsService.updateOverheadType(editOt.id, data);
    } else {
      await settingsService.createOverheadType(data);
    }
    setDialogVisible(false);
    loadOverheadTypes();
  }

  async function saveWorkRule() {
    setSavingRule(true);
    try {
      await settingsService.updateWorkRules(workRule);
    } finally {
      setSavingRule(false);
    }
  }

  return (
    <div>
      <BasePageHeader title="시스템 설정" />
      <TabView>
        <TabPanel header="Overhead Types">
          <BaseCrudTable value={overheadTypes} loading={loading}
            toolbarLeft={<Button label="추가" icon="pi pi-plus" size="small" onClick={openCreate} />}>
            <Column field="code" header="코드" sortable />
            <Column field="name" header="이름" sortable />
            <Column field="isActive" header="상태" body={(row) => <Tag value={row.isActive ? '활성' : '비활성'} severity={row.isActive ? 'success' : 'secondary'} />} />
            <Column header="" body={(row) => <Button icon="pi pi-pencil" text size="small" onClick={() => openEdit(row)} />} style={{ width: '4rem' }} />
          </BaseCrudTable>
        </TabPanel>

        <TabPanel header="Work Rules">
          <Card>
            <div className="form-grid">
              <div className="col-4 form-field">
                <label className="form-field__label">최소 일일 시수</label>
                <InputNumber value={workRule.minDailyHours} onValueChange={(e) => setWorkRule({ ...workRule, minDailyHours: e.value ?? 0 })} min={0} max={24} suffix="h" />
              </div>
              <div className="col-4 form-field">
                <label className="form-field__label">최대 주간 시수</label>
                <InputNumber value={workRule.maxWeeklyHours} onValueChange={(e) => setWorkRule({ ...workRule, maxWeeklyHours: e.value ?? 0 })} min={0} max={168} suffix="h" />
              </div>
              <div className="col-4 form-field">
                <label className="form-field__label">Location</label>
                <span style={{ padding: '0.5rem 0' }}>{workRule.location ?? '-'}</span>
              </div>
              <div className="col-12">
                <Button label="저장" icon="pi pi-save" loading={savingRule} onClick={saveWorkRule} />
              </div>
            </div>
          </Card>
        </TabPanel>
      </TabView>

      <OverheadTypeDialog visible={dialogVisible} onHide={() => setDialogVisible(false)} overheadType={editOt} onSave={onSaveOt} />
    </div>
  );
}
