"use client";

import React, { useState, useEffect } from "react";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { CustomerItemMappingConfig } from "./types";
import { tableTypeApi } from "@/lib/api/screen";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Plus, X } from "lucide-react";

export interface CustomerItemMappingConfigPanelProps {
  config: CustomerItemMappingConfig;
  onChange: (config: CustomerItemMappingConfig) => void;
}

export const CustomerItemMappingConfigPanel: React.FC<
  CustomerItemMappingConfigPanelProps
> = ({ config, onChange }) => {
  const [tables, setTables] = useState<any[]>([]);
  const [availableColumns, setAvailableColumns] = useState<any[]>([]);

  // 테이블 목록 로드
  useEffect(() => {
    const loadTables = async () => {
      try {
        const tableList = await tableTypeApi.getTables();
        setTables(tableList);
      } catch (error) {
        console.error("테이블 목록 로드 실패:", error);
      }
    };
    loadTables();
  }, []);

  // 선택된 테이블의 컬럼 목록 로드
  useEffect(() => {
    if (config.selectedTable) {
      const loadColumns = async () => {
        try {
          const columns = await tableTypeApi.getColumns(config.selectedTable!);
          setAvailableColumns(columns);
        } catch (error) {
          console.error("컬럼 목록 로드 실패:", error);
        }
      };
      loadColumns();
    }
  }, [config.selectedTable]);

  const handleTableChange = (tableName: string) => {
    onChange({
      ...config,
      selectedTable: tableName,
      columns: [], // 테이블 변경 시 컬럼 초기화
    });
  };

  const handleAddColumn = (columnName: string) => {
    if (!config.columns.includes(columnName)) {
      onChange({
        ...config,
        columns: [...config.columns, columnName],
      });
    }
  };

  const handleRemoveColumn = (columnName: string) => {
    onChange({
      ...config,
      columns: config.columns.filter((col) => col !== columnName),
    });
  };

  return (
    <div className="space-y-6 p-4">
      {/* 테이블 선택 */}
      <div className="space-y-2">
        <Label>테이블 선택</Label>
        <Select value={config.selectedTable} onValueChange={handleTableChange}>
          <SelectTrigger>
            <SelectValue placeholder="테이블을 선택하세요" />
          </SelectTrigger>
          <SelectContent>
            {tables.map((table) => (
              <SelectItem key={table.tableName} value={table.tableName}>
                {table.displayName || table.tableName}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      {/* 컬럼 설정 */}
      <div className="space-y-2">
        <Label>표시할 컬럼</Label>
        <div className="space-y-2">
          {/* 선택된 컬럼 목록 */}
          {config.columns.length > 0 && (
            <div className="border-border space-y-1 rounded border p-2">
              {config.columns.map((col, index) => (
                <div
                  key={col}
                  className="bg-muted flex items-center justify-between rounded px-2 py-1"
                >
                  <span className="text-sm">{col}</span>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => handleRemoveColumn(col)}
                    className="h-6 w-6 p-0"
                  >
                    <X className="h-3 w-3" />
                  </Button>
                </div>
              ))}
            </div>
          )}

          {/* 컬럼 추가 */}
          {availableColumns.length > 0 && (
            <Select onValueChange={handleAddColumn}>
              <SelectTrigger>
                <SelectValue placeholder="컬럼 추가" />
              </SelectTrigger>
              <SelectContent>
                {availableColumns
                  .filter((col) => !config.columns.includes(col.columnName))
                  .map((col) => (
                    <SelectItem key={col.columnName} value={col.columnName}>
                      {col.displayName || col.columnName}
                    </SelectItem>
                  ))}
              </SelectContent>
            </Select>
          )}
        </div>
      </div>

      {/* 체크박스 설정 */}
      <div className="space-y-3">
        <Label>체크박스 옵션</Label>
        <div className="space-y-2">
          <label className="flex items-center gap-2">
            <Checkbox
              checked={config.checkbox?.enabled !== false}
              onCheckedChange={(checked) =>
                onChange({
                  ...config,
                  checkbox: {
                    ...config.checkbox,
                    enabled: checked as boolean,
                  },
                })
              }
            />
            <span className="text-sm">체크박스 표시</span>
          </label>

          <label className="flex items-center gap-2">
            <Checkbox
              checked={config.checkbox?.selectAll !== false}
              onCheckedChange={(checked) =>
                onChange({
                  ...config,
                  checkbox: {
                    ...config.checkbox,
                    selectAll: checked as boolean,
                  },
                })
              }
            />
            <span className="text-sm">전체 선택 표시</span>
          </label>

          <label className="flex items-center gap-2">
            <Checkbox
              checked={config.checkbox?.multiple !== false}
              onCheckedChange={(checked) =>
                onChange({
                  ...config,
                  checkbox: {
                    ...config.checkbox,
                    multiple: checked as boolean,
                  },
                })
              }
            />
            <span className="text-sm">다중 선택 허용</span>
          </label>
        </div>
      </div>

      {/* 검색 영역 설정 */}
      <div className="space-y-3">
        <Label>검색/필터 영역</Label>
        
        <label className="flex items-center gap-2">
          <Checkbox
            checked={config.showSearchArea === true}
            onCheckedChange={(checked) =>
              onChange({
                ...config,
                showSearchArea: checked as boolean,
              })
            }
          />
          <span className="text-sm font-medium">
            검색/필터 영역 표시
          </span>
        </label>

        {config.showSearchArea && (
          <div className="space-y-2 pl-6">
            <Label className="text-xs">영역 높이 (px)</Label>
            <Input
              type="number"
              value={config.searchAreaHeight || 80}
              onChange={(e) =>
                onChange({
                  ...config,
                  searchAreaHeight: parseInt(e.target.value) || 80,
                })
              }
              min={60}
              max={200}
              className="h-8 text-xs"
            />
            <p className="text-muted-foreground text-[10px]">
              권장: 80-120px (나중에 검색창과 카테고리 필터 추가 예정)
            </p>
          </div>
        )}
      </div>

      {/* 빈 데이터 메시지 */}
      <div className="space-y-2">
        <Label>빈 데이터 메시지</Label>
        <Input
          value={config.emptyMessage || ""}
          onChange={(e) =>
            onChange({ ...config, emptyMessage: e.target.value })
          }
          placeholder="데이터가 없습니다"
        />
      </div>

      <div className="space-y-2">
        <Label>빈 데이터 설명</Label>
        <Input
          value={config.emptyDescription || ""}
          onChange={(e) =>
            onChange({ ...config, emptyDescription: e.target.value })
          }
          placeholder="품목 데이터가 추가되면 여기에 표시됩니다"
        />
      </div>
    </div>
  );
};

