"use client";

import React, { useState, useEffect, useMemo } from "react";
import { getChosung } from "../inbound/SupplierModal";

/* ------------------------------------------------------------------ */
/* Types                                                               */
/* ------------------------------------------------------------------ */

export interface EquipmentItem {
  id: string;
  equipment_code: string;
  equipment_name: string;
}

interface EquipmentModalProps {
  open: boolean;
  onClose: () => void;
  onSelect: (equipment: EquipmentItem) => void;
  items: EquipmentItem[];
  loading?: boolean;
  title?: string;
  searchPlaceholder?: string;
}

/* ------------------------------------------------------------------ */
/* Helpers                                                             */
/* ------------------------------------------------------------------ */

const AVATAR_COLORS = [
  "#3b82f6", "#22c55e", "#f59e0b", "#ef4444", "#8b5cf6",
  "#06b6d4", "#ec4899", "#14b8a6", "#f97316", "#6366f1",
  "#84cc16", "#e11d48", "#0ea5e9", "#a855f7", "#10b981",
];

function getAvatarColor(name: string): string {
  let hash = 0;
  for (let i = 0; i < name.length; i++) {
    hash = name.charCodeAt(i) + ((hash << 5) - hash);
  }
  return AVATAR_COLORS[Math.abs(hash) % AVATAR_COLORS.length];
}

/* ------------------------------------------------------------------ */
/* Component                                                           */
/* ------------------------------------------------------------------ */

export function EquipmentModal({
  open,
  onClose,
  onSelect,
  items,
  loading = false,
  title = "설비 선택",
  searchPlaceholder = "설비명 또는 코드 검색...",
}: EquipmentModalProps) {
  const [search, setSearch] = useState("");
  const [sortMode, setSortMode] = useState<"korean" | "abc">("korean");

  useEffect(() => {
    if (open) setSearch("");
  }, [open]);

  const grouped = useMemo(() => {
    const filtered = items.filter((e) =>
      e.equipment_name.toLowerCase().includes(search.toLowerCase()) ||
      e.equipment_code.toLowerCase().includes(search.toLowerCase())
    );

    const sorted = [...filtered].sort((a, b) => {
      if (sortMode === "abc") return a.equipment_name.localeCompare(b.equipment_name, "en");
      return a.equipment_name.localeCompare(b.equipment_name, "ko");
    });

    const groups: { letter: string; items: EquipmentItem[] }[] = [];
    const map = new Map<string, EquipmentItem[]>();
    for (const e of sorted) {
      const first = e.equipment_name.trim().charAt(0);
      const letter = getChosung(first);
      if (!map.has(letter)) map.set(letter, []);
      map.get(letter)!.push(e);
    }
    for (const [letter, list] of map) {
      groups.push({ letter, items: list });
    }
    return groups;
  }, [items, search, sortMode]);

  if (!open) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      <div className="absolute inset-0 bg-black/50" onClick={onClose} />

      <div className="relative bg-white rounded-2xl w-[80vw] h-[80vh] flex flex-col shadow-2xl overflow-hidden z-10">
        <div className="flex items-center justify-between px-5 py-4 border-b border-gray-100">
          <div className="flex items-center gap-3">
            <h3 className="text-lg font-bold text-gray-900">{title}</h3>
            <div className="flex gap-1.5">
              <button
                onClick={() => setSortMode("korean")}
                className={`px-3 py-1 rounded-full text-xs font-medium border transition-all ${
                  sortMode === "korean"
                    ? "bg-gray-900 text-white border-gray-900"
                    : "bg-white text-gray-500 border-gray-200 hover:bg-gray-50"
                }`}
              >
                가나다
              </button>
              <button
                onClick={() => setSortMode("abc")}
                className={`px-3 py-1 rounded-full text-xs font-medium border transition-all ${
                  sortMode === "abc"
                    ? "bg-gray-900 text-white border-gray-900"
                    : "bg-white text-gray-500 border-gray-200 hover:bg-gray-50"
                }`}
              >
                ABC
              </button>
            </div>
          </div>
          <button
            onClick={onClose}
            className="w-8 h-8 rounded-lg bg-gray-100 flex items-center justify-center text-gray-500 hover:bg-gray-200 transition-colors"
          >
            <svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>

        <div className="px-5 py-3">
          <div className="relative">
            <svg className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" d="M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z" />
            </svg>
            <input
              type="text"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder={searchPlaceholder}
              className="w-full pl-10 pr-4 py-2.5 border border-gray-200 rounded-xl text-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100 transition-all"
            />
          </div>
        </div>

        <div className="flex-1 overflow-y-auto px-5 pb-5">
          {loading ? (
            <div className="flex items-center justify-center py-12 text-sm text-gray-400">
              불러오는 중...
            </div>
          ) : grouped.length === 0 ? (
            <div className="flex items-center justify-center py-12 text-sm text-gray-400">
              {search ? "검색 결과가 없습니다" : "등록된 설비가 없습니다"}
            </div>
          ) : (
            grouped.map((group) => (
              <div key={group.letter} className="mb-2">
                <div className="flex items-center gap-2 mb-1">
                  <span className="text-sm font-bold text-blue-500 min-w-[20px]">{group.letter}</span>
                  <div className="flex-1 h-px bg-gray-100" />
                </div>
                <div className="grid grid-cols-4 min-[900px]:grid-cols-5 gap-x-2 gap-y-1">
                  {group.items.map((equipment) => {
                    const displayName = equipment.equipment_name.trim();
                    const initial = displayName.charAt(0);
                    const color = getAvatarColor(equipment.equipment_name);

                    return (
                      <button
                        key={equipment.id}
                        onClick={() => { onSelect(equipment); onClose(); }}
                        className="flex flex-col items-center gap-1 py-1.5 px-3 w-full rounded-xl hover:bg-gray-50 active:scale-95 transition-all cursor-pointer border-none bg-transparent"
                      >
                        <div
                          className="w-16 h-16 sm:w-20 sm:h-20 rounded-2xl flex items-center justify-center text-white text-xl sm:text-2xl font-bold shadow-sm shrink-0"
                          style={{ background: color }}
                        >
                          {initial}
                        </div>
                        <span className="text-xs sm:text-sm font-medium text-gray-700 text-center leading-tight w-full truncate px-1">
                          {equipment.equipment_name}
                        </span>
                      </button>
                    );
                  })}
                </div>
              </div>
            ))
          )}
        </div>
      </div>
    </div>
  );
}
