"use client";

import React, { useState } from "react";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Trash2, Plus } from "lucide-react";
import { AccordionBasicConfig, AccordionItem, DataSourceConfig, ContentFieldConfig } from "./types";

export interface AccordionBasicConfigPanelProps {
  config: AccordionBasicConfig;
  onChange: (config: Partial<AccordionBasicConfig>) => void;
  screenTableName?: string; // 화면에서 지정한 테이블명
  tableColumns?: any[]; // 테이블 컬럼 정보
}

/**
 * AccordionBasic 설정 패널
 * 컴포넌트의 설정값들을 편집할 수 있는 UI 제공
 */
export const AccordionBasicConfigPanel: React.FC<AccordionBasicConfigPanelProps> = ({
  config,
  onChange,
  screenTableName,
  tableColumns,
}) => {
  const [localItems, setLocalItems] = useState<AccordionItem[]>(
    config.items || [
      {
        id: "item-1",
        title: "제품 정보",
        content: "우리의 주력 제품은 최첨단 기술과 세련된 디자인을 결합합니다.",
        defaultOpen: true,
      },
    ],
  );

  const handleChange = (key: keyof AccordionBasicConfig, value: any) => {
    onChange({ [key]: value });
  };

  const handleItemsChange = (newItems: AccordionItem[]) => {
    setLocalItems(newItems);
    handleChange("items", newItems);
  };

  const addItem = () => {
    const newItem: AccordionItem = {
      id: `item-${Date.now()}`,
      title: "새 아이템",
      content: "새 아이템의 내용을 입력하세요.",
      defaultOpen: false,
    };
    handleItemsChange([...localItems, newItem]);
  };

  const removeItem = (itemId: string) => {
    handleItemsChange(localItems.filter((item) => item.id !== itemId));
  };

  const updateItem = (itemId: string, updates: Partial<AccordionItem>) => {
    handleItemsChange(localItems.map((item) => (item.id === itemId ? { ...item, ...updates } : item)));
  };

  return (
    <div className="space-y-4">
      <div className="text-sm font-medium">아코디언 설정</div>

      {/* 데이터 소스 설정 */}
      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="text-sm">데이터 소스</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          {/* 데이터 소스 타입 */}
          <div className="space-y-2">
            <Label htmlFor="sourceType">데이터 소스 타입</Label>
            <Select
              value={config.dataSource?.sourceType || "static"}
              onValueChange={(value) =>
                handleChange("dataSource", {
                  ...config.dataSource,
                  sourceType: value as "static" | "table" | "api",
                })
              }
            >
              <SelectTrigger>
                <SelectValue placeholder="데이터 소스 선택" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="static">정적 데이터 (수동 입력)</SelectItem>
                <SelectItem value="table">테이블 데이터</SelectItem>
                <SelectItem value="api">API 데이터</SelectItem>
              </SelectContent>
            </Select>
          </div>

          {/* 테이블 데이터 설정 */}
          {config.dataSource?.sourceType === "table" && (
            <>
              {/* 테이블 선택 방식 */}
              <div className="space-y-2">
                <Label>테이블 선택</Label>
                <div className="flex items-center space-x-2">
                  <Checkbox
                    id="useScreenTable"
                    checked={config.dataSource?.useScreenTable !== false}
                    onCheckedChange={(checked) =>
                      handleChange("dataSource", {
                        ...config.dataSource,
                        useScreenTable: checked as boolean,
                      })
                    }
                  />
                  <Label htmlFor="useScreenTable" className="text-sm">
                    화면 테이블 사용 {screenTableName && `(${screenTableName})`}
                  </Label>
                </div>
              </div>

              {/* 직접 테이블명 입력 (화면 테이블을 사용하지 않을 때) */}
              {config.dataSource?.useScreenTable === false && (
                <div className="space-y-2">
                  <Label htmlFor="tableName">테이블명</Label>
                  <Input
                    id="tableName"
                    value={config.dataSource?.tableName || ""}
                    onChange={(e) =>
                      handleChange("dataSource", {
                        ...config.dataSource,
                        tableName: e.target.value,
                      })
                    }
                    placeholder="테이블명을 입력하세요"
                  />
                </div>
              )}

              {/* 필드 선택 */}
              <div className="grid grid-cols-2 gap-3">
                <div className="space-y-2">
                  <Label htmlFor="titleField">제목 필드</Label>
                  <Select
                    value={config.dataSource?.titleField || ""}
                    onValueChange={(value) =>
                      handleChange("dataSource", {
                        ...config.dataSource,
                        titleField: value,
                      })
                    }
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="제목 필드 선택" />
                    </SelectTrigger>
                    <SelectContent>
                      {tableColumns?.map((column) => (
                        <SelectItem key={column.columnName} value={column.columnName}>
                          {column.columnLabel || column.columnName}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="idField">ID 필드</Label>
                  <Select
                    value={config.dataSource?.idField || ""}
                    onValueChange={(value) =>
                      handleChange("dataSource", {
                        ...config.dataSource,
                        idField: value,
                      })
                    }
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="ID 필드 선택" />
                    </SelectTrigger>
                    <SelectContent>
                      {tableColumns?.map((column) => (
                        <SelectItem key={column.columnName} value={column.columnName}>
                          {column.columnLabel || column.columnName}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>

              {/* 내용 필드들 (여러개 가능) */}
              <div className="space-y-3">
                <div className="flex items-center justify-between">
                  <Label>내용 필드</Label>
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={() => {
                      const newContentFields = [
                        ...(config.dataSource?.contentFields || []),
                        { fieldName: "", label: "", separator: "\n" },
                      ];
                      handleChange("dataSource", {
                        ...config.dataSource,
                        contentFields: newContentFields,
                      });
                    }}
                    className="h-8"
                  >
                    <Plus className="mr-1 h-4 w-4" />
                    필드 추가
                  </Button>
                </div>

                {config.dataSource?.contentFields?.map((field, index) => (
                  <Card key={index} className="p-3">
                    <div className="space-y-2">
                      <div className="flex items-center justify-between">
                        <Label className="text-sm">내용 필드 {index + 1}</Label>
                        <Button
                          type="button"
                          variant="ghost"
                          size="sm"
                          onClick={() => {
                            const newContentFields =
                              config.dataSource?.contentFields?.filter((_, i) => i !== index) || [];
                            handleChange("dataSource", {
                              ...config.dataSource,
                              contentFields: newContentFields,
                            });
                          }}
                          className="h-8 w-8 p-0 text-destructive"
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>

                      <div className="grid grid-cols-2 gap-2">
                        <div>
                          <Label className="text-xs">필드</Label>
                          <Select
                            value={field.fieldName}
                            onValueChange={(value) => {
                              const newContentFields = [...(config.dataSource?.contentFields || [])];
                              newContentFields[index] = { ...field, fieldName: value };
                              handleChange("dataSource", {
                                ...config.dataSource,
                                contentFields: newContentFields,
                              });
                            }}
                          >
                            <SelectTrigger>
                              <SelectValue placeholder="필드 선택" />
                            </SelectTrigger>
                            <SelectContent>
                              {tableColumns?.map((column) => (
                                <SelectItem key={column.columnName} value={column.columnName}>
                                  {column.columnLabel || column.columnName}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        </div>

                        <div>
                          <Label className="text-xs">표시 라벨 (선택사항)</Label>
                          <Input
                            value={field.label || ""}
                            onChange={(e) => {
                              const newContentFields = [...(config.dataSource?.contentFields || [])];
                              newContentFields[index] = { ...field, label: e.target.value };
                              handleChange("dataSource", {
                                ...config.dataSource,
                                contentFields: newContentFields,
                              });
                            }}
                            placeholder="예: 설명"
                            className="text-xs"
                          />
                        </div>
                      </div>
                    </div>
                  </Card>
                ))}

                {(!config.dataSource?.contentFields || config.dataSource.contentFields.length === 0) && (
                  <div className="py-4 text-center text-sm text-muted-foreground">내용 필드를 추가해주세요</div>
                )}
              </div>

              <div className="space-y-2">
                <Label htmlFor="orderBy">정렬 기준</Label>
                <Select
                  value={config.dataSource?.orderBy || ""}
                  onValueChange={(value) =>
                    handleChange("dataSource", {
                      ...config.dataSource,
                      orderBy: value,
                    })
                  }
                >
                  <SelectTrigger>
                    <SelectValue placeholder="정렬 필드 선택" />
                  </SelectTrigger>
                  <SelectContent>
                    {tableColumns?.map((column) => (
                      <SelectItem key={`${column.columnName}_asc`} value={`${column.columnName} ASC`}>
                        {column.columnLabel || column.columnName} (오름차순)
                      </SelectItem>
                    ))}
                    {tableColumns?.map((column) => (
                      <SelectItem key={`${column.columnName}_desc`} value={`${column.columnName} DESC`}>
                        {column.columnLabel || column.columnName} (내림차순)
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div className="text-muted-foreground rounded-lg bg-primary/10 p-3 text-sm">
                💡 <strong>스크롤 처리:</strong> 모든 데이터가 표시되며, 컴포넌트 높이를 초과하는 경우 자동으로 스크롤이
                생성됩니다.
              </div>
            </>
          )}

          {/* API 데이터 설정 */}
          {config.dataSource?.sourceType === "api" && (
            <>
              <div className="space-y-2">
                <Label htmlFor="apiEndpoint">API 엔드포인트</Label>
                <Input
                  id="apiEndpoint"
                  value={config.dataSource?.apiEndpoint || ""}
                  onChange={(e) =>
                    handleChange("dataSource", {
                      ...config.dataSource,
                      apiEndpoint: e.target.value,
                    })
                  }
                  placeholder="/api/data/accordion-items"
                />
              </div>

              <div className="grid grid-cols-2 gap-3">
                <div className="space-y-2">
                  <Label htmlFor="titleField">제목 필드</Label>
                  <Input
                    id="titleField"
                    value={config.dataSource?.titleField || ""}
                    onChange={(e) =>
                      handleChange("dataSource", {
                        ...config.dataSource,
                        titleField: e.target.value,
                      })
                    }
                    placeholder="title"
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="contentField">내용 필드</Label>
                  <Input
                    id="contentField"
                    value={config.dataSource?.contentField || ""}
                    onChange={(e) =>
                      handleChange("dataSource", {
                        ...config.dataSource,
                        contentField: e.target.value,
                      })
                    }
                    placeholder="content"
                  />
                </div>
              </div>
            </>
          )}
        </CardContent>
      </Card>

      {/* 기본 설정 */}
      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="text-sm">기본 설정</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          {/* 타입 설정 */}
          <div className="space-y-2">
            <Label htmlFor="type">선택 타입</Label>
            <Select
              value={config.type || "single"}
              onValueChange={(value) => handleChange("type", value as "single" | "multiple")}
            >
              <SelectTrigger>
                <SelectValue placeholder="선택 타입" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="single">단일 선택</SelectItem>
                <SelectItem value="multiple">다중 선택</SelectItem>
              </SelectContent>
            </Select>
          </div>

          {/* 접을 수 있는지 설정 */}
          <div className="flex items-center space-x-2">
            <Checkbox
              id="collapsible"
              checked={config.collapsible !== false}
              onCheckedChange={(checked) => handleChange("collapsible", checked)}
            />
            <Label htmlFor="collapsible">모든 아이템 접기 가능</Label>
          </div>

          {/* 기본값 설정 */}
          <div className="space-y-2">
            <Label htmlFor="defaultValue">기본으로 열린 아이템</Label>
            <Select
              value={config.defaultValue || "none"}
              onValueChange={(value) => handleChange("defaultValue", value === "none" ? undefined : value)}
            >
              <SelectTrigger>
                <SelectValue placeholder="기본으로 열린 아이템 선택" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="none">없음</SelectItem>
                {localItems.map((item) => (
                  <SelectItem key={item.id} value={item.id}>
                    {item.title}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          {/* 비활성화 */}
          <div className="flex items-center space-x-2">
            <Checkbox
              id="disabled"
              checked={config.disabled || false}
              onCheckedChange={(checked) => handleChange("disabled", checked)}
            />
            <Label htmlFor="disabled">비활성화</Label>
          </div>
        </CardContent>
      </Card>

      {/* 아이템 관리 (정적 데이터일 때만 표시) */}
      {(!config.dataSource || config.dataSource.sourceType === "static") && (
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="flex items-center justify-between text-sm">
              아이템 관리
              <Button type="button" variant="outline" size="sm" onClick={addItem} className="h-8">
                <Plus className="mr-1 h-4 w-4" />
                추가
              </Button>
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            {localItems.map((item, index) => (
              <Card key={item.id} className="p-4">
                <div className="space-y-3">
                  <div className="flex items-center justify-between">
                    <Label className="text-sm font-medium">아이템 {index + 1}</Label>
                    <Button
                      type="button"
                      variant="ghost"
                      size="sm"
                      onClick={() => removeItem(item.id)}
                      className="h-8 w-8 p-0 text-destructive hover:text-destructive"
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>

                  {/* 제목 */}
                  <div className="space-y-1">
                    <Label htmlFor={`title-${item.id}`} className="text-xs">
                      제목
                    </Label>
                    <Input
                      id={`title-${item.id}`}
                      value={item.title}
                      onChange={(e) => updateItem(item.id, { title: e.target.value })}
                      placeholder="아이템 제목"
                    />
                  </div>

                  {/* 내용 */}
                  <div className="space-y-1">
                    <Label htmlFor={`content-${item.id}`} className="text-xs">
                      내용
                    </Label>
                    <Textarea
                      id={`content-${item.id}`}
                      value={item.content}
                      onChange={(e) => updateItem(item.id, { content: e.target.value })}
                      placeholder="아이템 내용"
                      rows={3}
                    />
                  </div>

                  {/* 기본으로 열림 */}
                  <div className="flex items-center space-x-2">
                    <Checkbox
                      id={`defaultOpen-${item.id}`}
                      checked={item.defaultOpen || false}
                      onCheckedChange={(checked) => updateItem(item.id, { defaultOpen: checked as boolean })}
                    />
                    <Label htmlFor={`defaultOpen-${item.id}`} className="text-xs">
                      기본으로 열림
                    </Label>
                  </div>
                </div>
              </Card>
            ))}

            {localItems.length === 0 && (
              <div className="py-8 text-center text-muted-foreground">
                <p className="text-sm">아이템이 없습니다.</p>
                <p className="text-xs">위의 추가 버튼을 클릭하여 아이템을 추가하세요.</p>
              </div>
            )}
          </CardContent>
        </Card>
      )}
    </div>
  );
};
