"use client";

import React from "react";
import { X } from "lucide-react";
import { Equipment, Process } from "./types";

interface PopProcessModalProps {
  isOpen: boolean;
  selectedEquipment: Equipment | null;
  selectedProcess: Process | null;
  processes: Process[];
  onSelect: (process: Process) => void;
  onClose: () => void;
}

export function PopProcessModal({
  isOpen,
  selectedEquipment,
  selectedProcess,
  processes,
  onSelect,
  onClose,
}: PopProcessModalProps) {
  const [tempSelected, setTempSelected] = React.useState<Process | null>(selectedProcess);

  React.useEffect(() => {
    setTempSelected(selectedProcess);
  }, [selectedProcess, isOpen]);

  const handleConfirm = () => {
    if (tempSelected) {
      onSelect(tempSelected);
      onClose();
    }
  };

  if (!isOpen || !selectedEquipment) return null;

  // 선택된 설비의 공정만 필터링
  const availableProcesses = selectedEquipment.processIds.map((processId, index) => {
    const process = processes.find((p) => p.id === processId);
    return {
      id: processId,
      name: selectedEquipment.processNames[index],
      code: process?.code || "",
    };
  });

  return (
    <div className="pop-modal-overlay active" onClick={(e) => e.target === e.currentTarget && onClose()}>
      <div className="pop-modal">
        <div className="pop-modal-header">
          <h2 className="pop-modal-title">공정 선택</h2>
          <button className="pop-modal-close" onClick={onClose}>
            <X size={16} />
          </button>
        </div>

        <div className="pop-modal-body">
          <div className="pop-selection-grid">
            {availableProcesses.map((process) => (
              <div
                key={process.id}
                className={`pop-selection-card ${tempSelected?.id === process.id ? "selected" : ""}`}
                onClick={() => setTempSelected(process as Process)}
              >
                <div className="pop-selection-card-check">✓</div>
                <div className="pop-selection-card-name">{process.name}</div>
                <div className="pop-selection-card-info">{process.code}</div>
              </div>
            ))}
          </div>
        </div>

        <div className="pop-modal-footer">
          <button className="pop-btn pop-btn-outline" style={{ flex: 1 }} onClick={onClose}>
            취소
          </button>
          <button
            className="pop-btn pop-btn-primary"
            style={{ flex: 1 }}
            onClick={handleConfirm}
            disabled={!tempSelected}
          >
            확인
          </button>
        </div>
      </div>
    </div>
  );
}

