'use client';

import { useState, useEffect } from 'react';
import { Plus, Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import type { ApprovalPerson, StepType } from './types';
import { getEmployees } from './actions';

interface ApprovalLineSectionProps {
  data: ApprovalPerson[];
  onChange: (data: ApprovalPerson[]) => void;
}

const STEP_TYPE_OPTIONS: { value: StepType; label: string }[] = [
  { value: 'approval', label: '결재' },
  { value: 'agreement', label: '합의' },
];

export function ApprovalLineSection({ data, onChange }: ApprovalLineSectionProps) {
  const [employees, setEmployees] = useState<ApprovalPerson[]>([]);

  // 직원 목록 로드
  useEffect(() => {
    getEmployees().then(setEmployees);
  }, []);

  const handleAdd = () => {
    const newPerson: ApprovalPerson = {
      id: `temp-${Date.now()}`,
      department: '',
      position: '',
      name: '',
      stepType: 'approval',
    };
    onChange([...data, newPerson]);
  };

  const handleRemove = (index: number) => {
    onChange(data.filter((_, i) => i !== index));
  };

  const handleChange = (index: number, employeeId: string) => {
    const employee = employees.find((e) => e.id === employeeId);
    if (employee) {
      const newData = [...data];
      newData[index] = { ...employee, stepType: newData[index].stepType || 'approval' };
      onChange(newData);
    }
  };

  const handleStepTypeChange = (index: number, stepType: StepType) => {
    const newData = [...data];
    newData[index] = { ...newData[index], stepType };
    onChange(newData);
  };

  return (
    <div className="bg-white rounded-lg border p-6">
      <div className="flex items-center justify-between mb-4">
        <h3 className="text-lg font-semibold">결재선</h3>
        <Button variant="outline" size="sm" onClick={handleAdd}>
          <Plus className="w-4 h-4 mr-1" />
          추가
        </Button>
      </div>

      <div className="space-y-3">
        <div className="grid grid-cols-[2rem_5rem_1fr_2.25rem] gap-2 text-sm text-gray-500 mb-2">
          <span className="text-center">순</span>
          <span>유형</span>
          <span>부서 / 직책 / 이름</span>
          <span />
        </div>

        {data.length === 0 ? (
          <div className="text-center py-4 text-gray-400">
            결재선을 추가해주세요
          </div>
        ) : (
          data.map((person, index) => (
            <div key={`${person.id}-${index}`} className="grid grid-cols-[2rem_5rem_1fr_2.25rem] gap-2 items-center">
              <span className="text-center text-sm text-gray-500">{index + 1}</span>

              {/* 결재/합의 선택 */}
              <Select
                value={person.stepType || 'approval'}
                onValueChange={(value) => handleStepTypeChange(index, value as StepType)}
              >
                <SelectTrigger className="h-9 text-xs px-2">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {STEP_TYPE_OPTIONS.map((option) => (
                    <SelectItem key={option.value} value={option.value}>
                      {option.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>

              {/* 직원 선택 */}
              <Select
                value={person.id.startsWith('temp-') ? undefined : person.id}
                onValueChange={(value) => handleChange(index, value)}
              >
                <SelectTrigger>
                  <SelectValue
                    placeholder={
                      person.name && !person.id.startsWith('temp-')
                        ? `${person.department || ''} / ${person.position || ''} / ${person.name}`
                        : "부서명 / 직책명 / 이름 ▼"
                    }
                  />
                </SelectTrigger>
                <SelectContent>
                  {employees.map((employee) => (
                    <SelectItem key={employee.id} value={employee.id}>
                      {employee.department || ''} / {employee.position || ''} / {employee.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>

              <Button
                variant="ghost"
                size="icon"
                className="h-9 w-9 text-red-500 hover:text-red-700 hover:bg-red-50"
                onClick={() => handleRemove(index)}
              >
                <Trash2 className="w-4 h-4" />
              </Button>
            </div>
          ))
        )}
      </div>
    </div>
  );
}
