"use client";

import React, { useState, useRef, useEffect, useMemo } from "react";
import ModalCloseSvg from "@/app/svgs/closexsvg";
import DropdownIcon from "@/app/svgs/dropdownicon";
import { getInstructors, type UserRow } from "@/app/admin/id/mockData";
import { type Course } from "./mockData";

type Props = {
  open: boolean;
  onClose: () => void;
  onSave?: (courseName: string, instructorName: string) => void;
  onDelete?: () => void;
  editingCourse?: Course | null;
};

export default function CourseRegistrationModal({ open, onClose, onSave, onDelete, editingCourse }: Props) {
  const [courseName, setCourseName] = useState("");
  const [instructorId, setInstructorId] = useState<string>("");
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [isDeleteConfirmOpen, setIsDeleteConfirmOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);
  const modalRef = useRef<HTMLDivElement>(null);

  // 강사 목록 가져오기
  const [instructors, setInstructors] = useState<UserRow[]>([]);
  const [isLoadingInstructors, setIsLoadingInstructors] = useState(false);
  
  useEffect(() => {
    async function loadInstructors() {
      setIsLoadingInstructors(true);
      try {
        const data = await getInstructors();
        setInstructors(data);
      } catch (error) {
        console.error('강사 목록 로드 오류:', error);
        setInstructors([]);
      } finally {
        setIsLoadingInstructors(false);
      }
    }
    
    if (open) {
      loadInstructors();
    }
  }, [open]);
  
  // 선택된 강사 정보
  const selectedInstructor = useMemo(() => {
    return instructors.find(inst => inst.id === instructorId);
  }, [instructors, instructorId]);

  // 수정 모드일 때 기존 데이터 채우기
  useEffect(() => {
    if (open && editingCourse) {
      setCourseName(editingCourse.courseName);
      // 강사명으로 instructorId 찾기
      const instructor = instructors.find(inst => inst.name === editingCourse.instructorName);
      if (instructor) {
        setInstructorId(instructor.id);
      }
    } else if (!open) {
      setCourseName("");
      setInstructorId("");
      setIsDropdownOpen(false);
      setErrors({});
      setIsDeleteConfirmOpen(false);
    }
  }, [open, editingCourse, instructors]);

  // 외부 클릭 시 드롭다운 닫기
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        dropdownRef.current &&
        !dropdownRef.current.contains(event.target as Node)
      ) {
        setIsDropdownOpen(false);
      }
    };

    if (isDropdownOpen) {
      document.addEventListener("mousedown", handleClickOutside);
    }

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [isDropdownOpen]);

  // 모달 클릭 시 이벤트 전파 방지
  const handleModalClick = (e: React.MouseEvent) => {
    e.stopPropagation();
  };

  // 저장 버튼 클릭 핸들러
  const handleSave = () => {
    const nextErrors: Record<string, string> = {};
    
    if (!courseName.trim()) {
      nextErrors.courseName = "교육 과정명을 입력해 주세요.";
    }
    if (!instructorId || !selectedInstructor) {
      nextErrors.instructor = "강사를 선택해 주세요.";
    }
    
    setErrors(nextErrors);
    
    if (Object.keys(nextErrors).length > 0) {
      return;
    }
    
    if (onSave && selectedInstructor) {
      onSave(courseName.trim(), selectedInstructor.name);
    }
  };

  // 삭제 버튼 클릭 핸들러
  const handleDeleteClick = () => {
    setIsDeleteConfirmOpen(true);
  };

  // 삭제 확인 핸들러
  const handleDeleteConfirm = () => {
    if (onDelete) {
      onDelete();
      setIsDeleteConfirmOpen(false);
      onClose();
    }
  };

  // 삭제 취소 핸들러
  const handleDeleteCancel = () => {
    setIsDeleteConfirmOpen(false);
  };

  if (!open) return null;

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center"
      aria-hidden={!open}
      onClick={onClose}
    >
      <div
        className="absolute inset-0 bg-black/40"
        aria-hidden="true"
      />
      <div
        ref={modalRef}
        className="relative z-10 shadow-xl"
        onClick={handleModalClick}
      >
        <div className="bg-white border border-[#dee1e6] rounded-[12px] w-full min-w-[480px] max-h-[90vh] overflow-y-auto">
          {/* Header */}
          <div className="flex items-center justify-between gap-[10px] p-6">
            <h2 className="text-[20px] font-bold leading-[1.5] text-[#333c47]">
              {editingCourse ? "교육과정 수정" : "과목 등록"}
            </h2>
            <button
              type="button"
              onClick={onClose}
              className="w-6 h-6 flex items-center justify-center cursor-pointer hover:opacity-80 shrink-0"
              aria-label="닫기"
            >
              <ModalCloseSvg />
            </button>
          </div>

          {/* Form Container */}
          <div className="px-6 py-0">
            <div className="flex flex-col gap-6">
              {/* 교육 과정명 */}
              <div className="flex flex-col gap-2">
                <label className="text-[15px] font-semibold leading-[1.5] text-[#6c7682] w-[100px]">
                  교육 과정명<span className="text-[#f64c4c]">*</span>
                </label>
                <input
                  type="text"
                  value={courseName}
                  onChange={(e) => {
                    setCourseName(e.target.value);
                    if (errors.courseName) {
                      setErrors((prev) => {
                        const next = { ...prev };
                        delete next.courseName;
                        return next;
                      });
                    }
                  }}
                  placeholder="교육 과정명을 입력해 주세요."
                  className={`h-[40px] px-3 py-2 border rounded-[8px] bg-white text-[16px] font-normal leading-[1.5] text-[#1b2027] placeholder:text-[#b1b8c0] focus:outline-none ${
                    errors.courseName
                      ? "border-[#f64c4c] focus:shadow-[inset_0_0_0_1px_#333c47]"
                      : "border-[#dee1e6] focus:shadow-[inset_0_0_0_1px_#333c47]"
                  }`}
                />
                {errors.courseName && (
                  <p className="text-[#f64c4c] text-[13px] leading-tight">{errors.courseName}</p>
                )}
              </div>

              {/* 강사 */}
              <div className="flex flex-col gap-2">
                <label className="text-[15px] font-semibold leading-[1.5] text-[#6c7682] w-[100px]">
                  강사<span className="text-[#f64c4c]">*</span>
                </label>
                <div className="relative" ref={dropdownRef}>
                  <button
                    type="button"
                    onClick={() => setIsDropdownOpen(!isDropdownOpen)}
                    className={`w-full h-[40px] px-3 py-2 border rounded-[8px] bg-white flex items-center justify-between text-left focus:outline-none focus:shadow-[inset_0_0_0_1px_#333c47] cursor-pointer ${
                      errors.instructor
                        ? "border-[#f64c4c]"
                        : "border-[#dee1e6]"
                    }`}
                  >
                    <span
                      className={`text-[16px] font-normal leading-[1.5] flex-1 ${
                        selectedInstructor ? "text-[#1b2027]" : "text-[#6c7682]"
                      }`}
                    >
                      {selectedInstructor?.name || "강사를 선택해 주세요."}
                    </span>
                    <DropdownIcon stroke="#8C95A1" className="shrink-0" />
                  </button>
                  {isDropdownOpen && (
                    <div className="absolute top-full left-0 right-0 mt-1 bg-white border border-[#dee1e6] rounded-[8px] shadow-lg z-20 max-h-[200px] overflow-y-auto">
                      {instructors.length === 0 ? (
                        <div className="px-3 py-2 text-[16px] font-normal leading-[1.5] text-[#6c7682] text-center">
                          등록된 강사가 없습니다.
                        </div>
                      ) : (
                        instructors.map((instructor, index) => (
                          <button
                            key={instructor.id}
                            type="button"
                            onClick={() => {
                              setInstructorId(instructor.id);
                              setIsDropdownOpen(false);
                              if (errors.instructor) {
                                setErrors((prev) => {
                                  const next = { ...prev };
                                  delete next.instructor;
                                  return next;
                                });
                              }
                            }}
                            className={`w-full px-3 py-2 text-left text-[16px] font-normal leading-[1.5] hover:bg-[#f1f3f5] transition-colors cursor-pointer ${
                              instructorId === instructor.id
                                ? "bg-[#ecf0ff] text-[#1f2b91] font-semibold"
                                : "text-[#1b2027]"
                            } ${
                              index === 0 ? "rounded-t-[8px]" : ""
                            } ${
                              index === instructors.length - 1 ? "rounded-b-[8px]" : ""
                            }`}
                          >
                            {instructor.name}
                          </button>
                        ))
                      )}
                    </div>
                  )}
                </div>
                {errors.instructor && (
                  <p className="text-[#f64c4c] text-[13px] leading-tight">{errors.instructor}</p>
                )}
              </div>

              {/* 과목 이미지 */}
              <div className="flex flex-col gap-2">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <label className="text-[15px] font-semibold leading-[1.5] text-[#6c7682] whitespace-pre">
                      과목 이미지
                    </label>
                    <span className="text-[13px] font-normal leading-[1.4] text-[#8c95a1]">
                      30MB 미만의 PNG, JPG
                    </span>
                  </div>
                </div>
                <div className="bg-gray-50 border border-[#dee1e6] border-dashed h-[192px] rounded-[8px] flex flex-col items-center justify-center gap-3 cursor-pointer hover:bg-gray-100 transition-colors px-0 py-4">
                  <div className="w-10 h-10 flex items-center justify-center shrink-0">
                    <svg
                      width="40"
                      height="40"
                      viewBox="0 0 40 40"
                      fill="none"
                      xmlns="http://www.w3.org/2000/svg"
                    >
                      <path
                        d="M20 13.3333V26.6667M13.3333 20H26.6667"
                        stroke="#8C95A1"
                        strokeWidth="2"
                        strokeLinecap="round"
                        strokeLinejoin="round"
                      />
                    </svg>
                  </div>
                  <div className="text-center">
                    <p className="text-[14px] font-normal leading-[1.5] text-[#8c95a1] whitespace-pre">
                      (클릭하여 이미지 업로드)
                      <br aria-hidden="true" />
                      미첨부 시 기본 이미지가 노출됩니다.
                    </p>
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* Actions Container */}
          <div className="flex flex-col gap-8 h-[96px] items-center p-6">
            <div className="flex items-center justify-center gap-3 w-full">
              {editingCourse && (
                <button
                  type="button"
                  onClick={handleDeleteClick}
                  className="h-[48px] px-4 rounded-[10px] bg-[#fef2f2] text-[16px] font-semibold leading-[1.5] text-[#f64c4c] w-[136px] hover:bg-[#fae6e6] transition-colors cursor-pointer"
                >
                  삭제
                </button>
              )}
              <button
                type="button"
                onClick={onClose}
                className="h-[48px] px-4 rounded-[10px] bg-[#f1f3f5] text-[16px] font-semibold leading-[1.5] text-[#4c5561] w-[136px] hover:bg-[#e5e7eb] transition-colors cursor-pointer"
              >
                취소
              </button>
              <button
                type="button"
                onClick={handleSave}
                className="h-[48px] px-4 rounded-[10px] bg-[#1f2b91] text-[16px] font-semibold leading-[1.5] text-white w-[136px] hover:bg-[#1a2478] transition-colors cursor-pointer"
              >
                저장
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* 삭제 확인 모달 */}
      {isDeleteConfirmOpen && (
        <div className="fixed inset-0 z-[60] flex items-center justify-center">
          <div 
            className="absolute inset-0 bg-black/40"
            onClick={handleDeleteCancel}
            aria-hidden="true"
          />
          <div className="relative z-10 bg-white rounded-[8px] p-[24px] shadow-[0px_8px_20px_0px_rgba(0,0,0,0.06),0px_24px_60px_0px_rgba(0,0,0,0.12)] flex flex-col gap-[32px] items-end justify-end min-w-[500px]">
            <div className="flex flex-col gap-[16px] items-start justify-center w-full">
              <h2 className="text-[18px] font-semibold leading-[1.5] text-[#333c47]">
                교육과정을 삭제하시겠습니까?
              </h2>
              <p className="text-[15px] font-normal leading-[1.5] text-[#4c5561]">
                삭제된 교육과정은 복구할 수 없습니다.
                <br />
                정말 삭제하시겠습니까?
              </p>
            </div>
            <div className="flex gap-2 items-center justify-end">
              <button
                type="button"
                onClick={handleDeleteCancel}
                className="h-[40px] px-2 rounded-[8px] bg-[#f1f3f5] text-[16px] font-semibold leading-[1.5] text-[#4c5561] w-[80px] hover:bg-[#e5e7eb] cursor-pointer transition-colors"
              >
                취소
              </button>
              <button
                type="button"
                onClick={handleDeleteConfirm}
                className="h-[40px] px-4 rounded-[8px] bg-[#fef2f2] text-[16px] font-semibold leading-[1.5] text-[#f64c4c] hover:bg-[#fae6e6] cursor-pointer transition-colors"
              >
                삭제하기
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

