"use client";

import React from "react";
import { ConfigPanelBuilderProps, ConfigSectionDefinition } from "./ConfigPanelTypes";
import { ConfigSection } from "./ConfigSection";
import { ConfigField } from "./ConfigField";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";

function renderSections<T extends Record<string, any>>(
  sections: ConfigSectionDefinition<T>[],
  config: T,
  onChange: (key: string, value: any) => void,
  tableColumns?: any[],
) {
  return sections.map((section) => {
    if (section.condition && !section.condition(config)) {
      return null;
    }

    const visibleFields = section.fields.filter(
      (field) => !field.condition || field.condition(config),
    );

    if (visibleFields.length === 0) {
      return null;
    }

    return (
      <ConfigSection key={section.id} section={section}>
        {visibleFields.map((field) => (
          <ConfigField
            key={field.key}
            field={field}
            value={(config as any)[field.key]}
            onChange={onChange}
            tableColumns={tableColumns}
          />
        ))}
      </ConfigSection>
    );
  });
}

export function ConfigPanelBuilder<T extends Record<string, any>>({
  config,
  onChange,
  onConfigChange,
  sections,
  presets,
  tableColumns,
  children,
  mode = "flat",
  context,
}: ConfigPanelBuilderProps<T>) {
  const effectiveTableColumns = tableColumns || context?.tableColumns;

  const presetSection = presets && presets.length > 0 && (
    <div className="border-b border-border/40 pb-2.5">
      <h4 className="mb-1.5 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
        빠른 설정
      </h4>
      <div className="flex flex-wrap gap-1">
        {presets.map((preset, idx) => (
          <button
            key={idx}
            onClick={() => {
              Object.entries(preset.values).forEach(([key, value]) => {
                onChange(key, value);
              });
              if (onConfigChange) {
                onConfigChange({ ...config, ...preset.values } as Record<string, any>);
              }
            }}
            className="rounded border border-border bg-background px-2 py-0.5 text-[10px] font-medium text-muted-foreground transition-colors hover:border-primary hover:text-primary"
            title={preset.description}
          >
            {preset.label}
          </button>
        ))}
      </div>
    </div>
  );

  if (mode === "tabs") {
    const groupMap = new Map<string, ConfigSectionDefinition<T>[]>();
    const ungrouped: ConfigSectionDefinition<T>[] = [];

    for (const section of sections) {
      if (section.group) {
        const existing = groupMap.get(section.group) || [];
        existing.push(section);
        groupMap.set(section.group, existing);
      } else {
        ungrouped.push(section);
      }
    }

    const tabGroups = Array.from(groupMap.entries());

    if (tabGroups.length === 0) {
      return (
        <div className="space-y-1">
          {presetSection}
          {renderSections(sections, config, onChange, effectiveTableColumns)}
          {children}
        </div>
      );
    }

    const defaultTab = tabGroups[0]?.[0] || "general";

    return (
      <div className="space-y-1">
        {presetSection}

        {ungrouped.length > 0 && renderSections(ungrouped, config, onChange, effectiveTableColumns)}

        <Tabs defaultValue={defaultTab} className="w-full">
          <TabsList className="h-7 w-full">
            {tabGroups.map(([groupName]) => (
              <TabsTrigger key={groupName} value={groupName} className="h-6 text-xs">
                {groupName}
              </TabsTrigger>
            ))}
          </TabsList>
          {tabGroups.map(([groupName, groupSections]) => (
            <TabsContent key={groupName} value={groupName} className="mt-1">
              {renderSections(groupSections, config, onChange, effectiveTableColumns)}
            </TabsContent>
          ))}
        </Tabs>

        {children}
      </div>
    );
  }

  return (
    <div className="space-y-1">
      {presetSection}
      {renderSections(sections, config, onChange, effectiveTableColumns)}
      {children}
    </div>
  );
}
