'use client';

import { useState, useCallback } from 'react';
import { X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import type { ElectronicApproval, ApprovalPerson } from '../types';

// 목업 부서 목록
const MOCK_DEPARTMENTS = [
  { value: 'sales', label: '영업부' },
  { value: 'production', label: '생산부' },
  { value: 'quality', label: '품질부' },
  { value: 'management', label: '경영지원부' },
];

// 목업 직책 목록
const MOCK_POSITIONS = [
  { value: 'staff', label: '사원' },
  { value: 'senior', label: '주임' },
  { value: 'assistant_manager', label: '대리' },
  { value: 'manager', label: '과장' },
  { value: 'deputy_manager', label: '차장' },
  { value: 'general_manager', label: '부장' },
  { value: 'director', label: '이사' },
  { value: 'ceo', label: '대표' },
];

// 목업 사원 목록
const MOCK_EMPLOYEES = [
  { value: 'hong', label: '홍길동' },
  { value: 'kim', label: '김철수' },
  { value: 'lee', label: '이영희' },
  { value: 'park', label: '박지영' },
  { value: 'choi', label: '최민수' },
];

interface ElectronicApprovalModalProps {
  isOpen: boolean;
  onClose: () => void;
  approval: ElectronicApproval;
  onSave: (approval: ElectronicApproval) => void;
}

export function ElectronicApprovalModal({
  isOpen,
  onClose,
  approval,
  onSave,
}: ElectronicApprovalModalProps) {
  const [localApproval, setLocalApproval] = useState<ElectronicApproval>(approval);

  // 결재자 추가
  const handleAddApprover = useCallback(() => {
    const newPerson: ApprovalPerson = {
      id: String(Date.now()),
      department: '',
      position: '',
      name: '',
    };
    setLocalApproval((prev) => ({
      ...prev,
      approvers: [...prev.approvers, newPerson],
    }));
  }, []);

  // 결재자 삭제
  const handleRemoveApprover = useCallback((personId: string) => {
    setLocalApproval((prev) => ({
      ...prev,
      approvers: prev.approvers.filter((p) => p.id !== personId),
    }));
  }, []);

  // 결재자 변경
  const handleApproverChange = useCallback(
    (personId: string, field: keyof ApprovalPerson, value: string) => {
      setLocalApproval((prev) => ({
        ...prev,
        approvers: prev.approvers.map((p) =>
          p.id === personId ? { ...p, [field]: value } : p
        ),
      }));
    },
    []
  );

  // 참조자 추가
  const handleAddReference = useCallback(() => {
    const newPerson: ApprovalPerson = {
      id: String(Date.now()),
      department: '',
      position: '',
      name: '',
    };
    setLocalApproval((prev) => ({
      ...prev,
      references: [...prev.references, newPerson],
    }));
  }, []);

  // 참조자 삭제
  const handleRemoveReference = useCallback((personId: string) => {
    setLocalApproval((prev) => ({
      ...prev,
      references: prev.references.filter((p) => p.id !== personId),
    }));
  }, []);

  // 참조자 변경
  const handleReferenceChange = useCallback(
    (personId: string, field: keyof ApprovalPerson, value: string) => {
      setLocalApproval((prev) => ({
        ...prev,
        references: prev.references.map((p) =>
          p.id === personId ? { ...p, [field]: value } : p
        ),
      }));
    },
    []
  );

  // 저장
  const handleSave = useCallback(() => {
    onSave(localApproval);
  }, [localApproval, onSave]);

  // 취소
  const handleCancel = useCallback(() => {
    setLocalApproval(approval);
    onClose();
  }, [approval, onClose]);

  // 사람 선택 행 렌더링
  const renderPersonRow = (
    person: ApprovalPerson,
    index: number,
    type: 'approver' | 'reference'
  ) => {
    const onChange =
      type === 'approver' ? handleApproverChange : handleReferenceChange;
    const onRemove =
      type === 'approver' ? handleRemoveApprover : handleRemoveReference;

    return (
      <div key={person.id} className="flex items-center gap-2">
        <Select
          value={person.department || undefined}
          onValueChange={(val) => onChange(person.id, 'department', val)}
        >
          <SelectTrigger className="min-w-[140px] w-auto">
            <SelectValue placeholder="부서명" />
          </SelectTrigger>
          <SelectContent>
            {MOCK_DEPARTMENTS.map((dept) => (
              <SelectItem key={dept.value} value={dept.value}>
                {dept.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
        <span className="text-gray-400">/</span>
        <Select
          value={person.position || undefined}
          onValueChange={(val) => onChange(person.id, 'position', val)}
        >
          <SelectTrigger className="min-w-[100px] w-auto">
            <SelectValue placeholder="직책명" />
          </SelectTrigger>
          <SelectContent>
            {MOCK_POSITIONS.map((pos) => (
              <SelectItem key={pos.value} value={pos.value}>
                {pos.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
        <span className="text-gray-400">/</span>
        <Select
          value={person.name || undefined}
          onValueChange={(val) => onChange(person.id, 'name', val)}
        >
          <SelectTrigger className="min-w-[100px] w-auto">
            <SelectValue placeholder="이름" />
          </SelectTrigger>
          <SelectContent>
            {MOCK_EMPLOYEES.map((emp) => (
              <SelectItem key={emp.value} value={emp.value}>
                {emp.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
        <Button
          type="button"
          variant="ghost"
          size="icon"
          className="h-8 w-8 text-blue-500 hover:text-blue-600 hover:bg-blue-50"
          onClick={() => onRemove(person.id)}
        >
          <X className="h-4 w-4" />
        </Button>
      </div>
    );
  };

  return (
    <Dialog open={isOpen} onOpenChange={(open) => !open && handleCancel()}>
      <DialogContent className="w-[95vw] max-w-[500px] sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle className="text-lg font-bold">전자결재</DialogTitle>
        </DialogHeader>

        <div className="space-y-6 py-4">
          {/* 결재선 */}
          <div className="space-y-3">
            <div className="flex items-center justify-between">
              <h3 className="font-medium">결재선</h3>
              <div className="flex items-center gap-2">
                <span className="text-sm text-gray-500">부서 / 직책 / 이름</span>
                <Button
                  type="button"
                  variant="outline"
                  size="sm"
                  onClick={handleAddApprover}
                >
                  추가
                </Button>
              </div>
            </div>
            <div className="space-y-2">
              {localApproval.approvers.length === 0 ? (
                <p className="text-sm text-gray-500 text-center py-4 border rounded-lg">
                  결재자를 추가해주세요.
                </p>
              ) : (
                localApproval.approvers.map((person, index) =>
                  renderPersonRow(person, index, 'approver')
                )
              )}
            </div>
          </div>

          {/* 참조 */}
          <div className="space-y-3">
            <div className="flex items-center justify-between">
              <h3 className="font-medium">참조</h3>
              <div className="flex items-center gap-2">
                <span className="text-sm text-gray-500">부서 / 직책 / 이름</span>
                <Button
                  type="button"
                  variant="outline"
                  size="sm"
                  onClick={handleAddReference}
                >
                  추가
                </Button>
              </div>
            </div>
            <div className="space-y-2">
              {localApproval.references.length === 0 ? (
                <p className="text-sm text-gray-500 text-center py-4 border rounded-lg">
                  참조자를 추가해주세요.
                </p>
              ) : (
                localApproval.references.map((person, index) =>
                  renderPersonRow(person, index, 'reference')
                )
              )}
            </div>
          </div>
        </div>

        <DialogFooter className="flex gap-2">
          <Button variant="outline" onClick={handleCancel}>
            취소
          </Button>
          <Button onClick={handleSave} className="bg-gray-800 hover:bg-gray-900">
            저장
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
