"use client";

import React, { useState } from "react";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Search, ExternalLink } from "lucide-react";
import { WebTypeComponentProps } from "@/lib/registry/types";
import { WidgetComponent, EntityTypeConfig } from "@/types/screen";

export const EntityWidget: React.FC<WebTypeComponentProps> = ({ component, value, onChange, readonly = false }) => {
  const widget = component as WidgetComponent;
  const { placeholder, required, style } = widget;
  const config = widget.webTypeConfig as EntityTypeConfig | undefined;

  const [searchTerm, setSearchTerm] = useState("");
  const [isSearchMode, setIsSearchMode] = useState(false);

  // 사용자가 테두리를 설정했는지 확인
  const hasCustomBorder = style && (style.borderWidth || style.borderStyle || style.borderColor || style.border);

  // 엔티티 목록 가져오기 (실제로는 API 호출)
  const getEntityOptions = () => {
    const entityType = config?.entityType || "default";

    // 예시 데이터 - 실제로는 API에서 데이터를 가져옴
    const entities = {
      customer: [
        { id: "CUST001", name: "삼성전자", code: "SAMSUNG", type: "대기업" },
        { id: "CUST002", name: "LG전자", code: "LG", type: "대기업" },
        { id: "CUST003", name: "SK하이닉스", code: "SKHYNIX", type: "대기업" },
      ],
      supplier: [
        { id: "SUPP001", name: "공급업체 A", code: "SUPPA", type: "협력사" },
        { id: "SUPP002", name: "공급업체 B", code: "SUPPB", type: "협력사" },
        { id: "SUPP003", name: "공급업체 C", code: "SUPPC", type: "협력사" },
      ],
      employee: [
        { id: "EMP001", name: "김철수", code: "KCS", type: "정규직" },
        { id: "EMP002", name: "이영희", code: "LYH", type: "정규직" },
        { id: "EMP003", name: "박민수", code: "PMS", type: "계약직" },
      ],
      default: [
        { id: "ENT001", name: "엔티티 1", code: "ENT1", type: "기본" },
        { id: "ENT002", name: "엔티티 2", code: "ENT2", type: "기본" },
        { id: "ENT003", name: "엔티티 3", code: "ENT3", type: "기본" },
      ],
    };

    return entities[entityType as keyof typeof entities] || entities.default;
  };

  const entityOptions = getEntityOptions();

  // 검색 필터링
  const filteredOptions = entityOptions.filter(
    (option) =>
      !searchTerm ||
      option.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      option.code.toLowerCase().includes(searchTerm.toLowerCase()),
  );

  // 선택된 엔티티 정보 찾기
  const selectedEntity = entityOptions.find((option) => option.id === value);

  // 검색 모드 토글
  const toggleSearchMode = () => {
    setIsSearchMode(!isSearchMode);
    setSearchTerm("");
  };

  // 상세 정보 보기 (팝업 등)
  const handleViewDetails = () => {
    if (selectedEntity) {
      // 실제로는 상세 정보 팝업 또는 새 창 열기
      alert(`${selectedEntity.name} 상세 정보`);
    }
  };

  return (
    <div className="h-full w-full space-y-2">
      {/* 검색 모드 */}
      {isSearchMode ? (
        <div className="flex space-x-2">
          <Input
            placeholder="엔티티 검색..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="flex-1"
          />
          <Button size="sm" variant="outline" onClick={toggleSearchMode}>
            닫기
          </Button>
        </div>
      ) : (
        <div className="flex space-x-2">
          {/* 엔티티 선택 */}
          <div className="flex-1">
            <Select value={value || ""} onValueChange={onChange} disabled={readonly} required={required}>
              <SelectTrigger className={`w-full ${hasCustomBorder ? "!border-0" : ""}`} style={style}>
                <SelectValue placeholder={placeholder || config?.placeholder || "엔티티를 선택하세요..."} />
              </SelectTrigger>
              <SelectContent>
                {filteredOptions.map((option) => (
                  <SelectItem key={option.id} value={option.id}>
                    <div className="flex items-center space-x-2">
                      <Badge variant="outline" className="text-xs">
                        {option.code}
                      </Badge>
                      <span>{option.name}</span>
                      <Badge variant="secondary" className="text-xs">
                        {option.type}
                      </Badge>
                    </div>
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          {/* 검색 버튼 */}
          <Button size="sm" variant="outline" onClick={toggleSearchMode} disabled={readonly}>
            <Search className="h-4 w-4" />
          </Button>

          {/* 상세보기 버튼 */}
          {selectedEntity && config?.showDetails && (
            <Button size="sm" variant="outline" onClick={handleViewDetails}>
              <ExternalLink className="h-4 w-4" />
            </Button>
          )}
        </div>
      )}

      {/* 선택된 엔티티 정보 표시 */}
      {selectedEntity && (
        <div className="bg-muted rounded-md p-2">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-2">
              <Badge variant="outline" className="text-xs">
                {selectedEntity.code}
              </Badge>
              <span className="text-sm font-medium">{selectedEntity.name}</span>
              <Badge variant="secondary" className="text-xs">
                {selectedEntity.type}
              </Badge>
            </div>

            {config?.allowClear && !readonly && (
              <Button size="sm" variant="ghost" onClick={() => onChange?.("")} className="h-6 w-6 p-0">
                ×
              </Button>
            )}
          </div>
        </div>
      )}

      {/* 엔티티 타입 표시 */}
      {config?.entityType && (
        <div className="flex items-center justify-between">
          <Badge variant="secondary" className="text-xs">
            {config.entityType}
          </Badge>

          {config?.allowMultiple && <span className="text-muted-foreground text-xs">다중 선택 가능</span>}
        </div>
      )}
    </div>
  );
};

EntityWidget.displayName = "EntityWidget";


