"use client";

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

interface PopEquipmentModalProps {
  isOpen: boolean;
  equipments: Equipment[];
  selectedEquipment: Equipment | null;
  onSelect: (equipment: Equipment) => void;
  onClose: () => void;
}

export function PopEquipmentModal({
  isOpen,
  equipments,
  selectedEquipment,
  onSelect,
  onClose,
}: PopEquipmentModalProps) {
  const [tempSelected, setTempSelected] = React.useState<Equipment | null>(selectedEquipment);

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

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

  if (!isOpen) return null;

  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">
            {equipments.map((equip) => (
              <div
                key={equip.id}
                className={`pop-selection-card ${tempSelected?.id === equip.id ? "selected" : ""}`}
                onClick={() => setTempSelected(equip)}
              >
                <div className="pop-selection-card-check">✓</div>
                <div className="pop-selection-card-name">{equip.name}</div>
                <div className="pop-selection-card-info">{equip.processNames.join(", ")}</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>
  );
}
