'use client';

import React, { useState } from 'react';
import { Settings, X, Eye, EyeOff, ListChecks } from 'lucide-react';
import { Switch } from '@/components/ui/switch';
import { cn } from '@/lib/utils';
import { ChecklistTemplateEditor } from './ChecklistTemplateEditor';
import type { ChecklistCategory } from '../types';

export interface AuditDisplaySettings {
  showProgressBar: boolean;
  showDocumentViewer: boolean;
  showDocumentSection: boolean;
  showCompletedItems: boolean;
  expandAllCategories: boolean;
}

// 점검표 관리 props
export interface ChecklistManagementProps {
  categories: ChecklistCategory[];
  hasChanges: boolean;
  saving: boolean;
  loading?: boolean;
  error?: string | null;
  onAddCategory: () => void;
  onUpdateCategoryTitle: (categoryId: string, title: string) => void;
  onDeleteCategory: (categoryId: string) => void;
  onMoveCategoryUp: (index: number) => void;
  onMoveCategoryDown: (index: number) => void;
  onAddSubItem: (categoryId: string) => void;
  onUpdateSubItemName: (categoryId: string, subItemId: string, name: string) => void;
  onDeleteSubItem: (categoryId: string, subItemId: string) => void;
  onMoveSubItemUp: (categoryId: string, index: number) => void;
  onMoveSubItemDown: (categoryId: string, index: number) => void;
  onSave: () => void;
  onReset: () => void;
}

interface AuditSettingsPanelProps {
  isOpen: boolean;
  onClose: () => void;
  settings: AuditDisplaySettings;
  onSettingsChange: (settings: AuditDisplaySettings) => void;
  checklistManagement?: ChecklistManagementProps;
}

type TabType = 'display' | 'checklist';

export function AuditSettingsPanel({
  isOpen,
  onClose,
  settings,
  onSettingsChange,
  checklistManagement,
}: AuditSettingsPanelProps) {
  const [activeTab, setActiveTab] = useState<TabType>('display');

  const handleToggle = (key: keyof AuditDisplaySettings) => {
    onSettingsChange({
      ...settings,
      [key]: !settings[key],
    });
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-start justify-end">
      {/* 배경 오버레이 */}
      <div
        className="absolute inset-0 bg-black/30"
        onClick={onClose}
      />

      {/* 설정 패널 */}
      <div className="relative w-80 h-full bg-white shadow-xl flex flex-col animate-slide-in-right">
        {/* 헤더 */}
        <div className="flex items-center justify-between px-4 py-3 border-b border-gray-200 bg-gray-50">
          <div className="flex items-center gap-2">
            <Settings className="h-5 w-5 text-gray-600" />
            <h3 className="font-semibold text-gray-900">설정</h3>
          </div>
          <button
            type="button"
            onClick={onClose}
            className="p-1.5 hover:bg-gray-200 rounded-lg transition-colors"
          >
            <X className="h-5 w-5 text-gray-500" />
          </button>
        </div>

        {/* 탭 */}
        <div className="flex border-b border-gray-200">
          <button
            type="button"
            onClick={() => setActiveTab('display')}
            className={cn(
              'flex-1 flex items-center justify-center gap-1.5 py-2.5 text-xs font-medium transition-colors',
              activeTab === 'display'
                ? 'text-blue-600 border-b-2 border-blue-600'
                : 'text-gray-500 hover:text-gray-700'
            )}
          >
            <Eye className="h-3.5 w-3.5" />
            화면 설정
          </button>
          <button
            type="button"
            onClick={() => setActiveTab('checklist')}
            className={cn(
              'flex-1 flex items-center justify-center gap-1.5 py-2.5 text-xs font-medium transition-colors',
              activeTab === 'checklist'
                ? 'text-blue-600 border-b-2 border-blue-600'
                : 'text-gray-500 hover:text-gray-700'
            )}
          >
            <ListChecks className="h-3.5 w-3.5" />
            점검표 관리
          </button>
        </div>

        {/* 탭 컨텐츠 */}
        <div className="flex-1 overflow-y-auto p-4">
          {activeTab === 'display' ? (
            <DisplaySettingsContent
              settings={settings}
              onToggle={handleToggle}
              onSettingsChange={onSettingsChange}
            />
          ) : checklistManagement ? (
            <ChecklistTemplateEditor
              categories={checklistManagement.categories}
              hasChanges={checklistManagement.hasChanges}
              saving={checklistManagement.saving}
              loading={checklistManagement.loading}
              error={checklistManagement.error}
              onAddCategory={checklistManagement.onAddCategory}
              onUpdateCategoryTitle={checklistManagement.onUpdateCategoryTitle}
              onDeleteCategory={checklistManagement.onDeleteCategory}
              onMoveCategoryUp={checklistManagement.onMoveCategoryUp}
              onMoveCategoryDown={checklistManagement.onMoveCategoryDown}
              onAddSubItem={checklistManagement.onAddSubItem}
              onUpdateSubItemName={checklistManagement.onUpdateSubItemName}
              onDeleteSubItem={checklistManagement.onDeleteSubItem}
              onMoveSubItemUp={checklistManagement.onMoveSubItemUp}
              onMoveSubItemDown={checklistManagement.onMoveSubItemDown}
              onSave={checklistManagement.onSave}
              onReset={checklistManagement.onReset}
            />
          ) : (
            <div className="flex items-center justify-center h-32 text-gray-400 text-sm">
              점검표 관리 데이터를 불러오는 중...
            </div>
          )}
        </div>

        {/* 하단 안내 (화면 설정 탭일 때만) */}
        {activeTab === 'display' && (
          <div className="px-4 py-3 border-t border-gray-200 bg-gray-50">
            <p className="text-xs text-gray-500">
              설정은 자동으로 저장됩니다
            </p>
          </div>
        )}
      </div>
    </div>
  );
}

// ===== 화면 설정 탭 컨텐츠 (기존 코드 분리) =====

interface DisplaySettingsContentProps {
  settings: AuditDisplaySettings;
  onToggle: (key: keyof AuditDisplaySettings) => void;
  onSettingsChange: (settings: AuditDisplaySettings) => void;
}

function DisplaySettingsContent({ settings, onToggle, onSettingsChange }: DisplaySettingsContentProps) {
  return (
    <div className="space-y-4">
      {/* 레이아웃 섹션 */}
      <div>
        <h4 className="text-sm font-medium text-gray-700 mb-3">레이아웃</h4>
        <div className="space-y-3">
          <SettingRow
            label="진행률 표시"
            description="상단 전체 심사 진행률 바를 표시합니다"
            checked={settings.showProgressBar}
            onChange={() => onToggle('showProgressBar')}
          />
          <SettingRow
            label="문서 뷰어"
            description="우측 문서 미리보기 패널을 표시합니다"
            checked={settings.showDocumentViewer}
            onChange={() => onToggle('showDocumentViewer')}
          />
          <SettingRow
            label="기준 문서화 섹션"
            description="중앙 기준 문서 목록 패널을 표시합니다"
            checked={settings.showDocumentSection}
            onChange={() => onToggle('showDocumentSection')}
          />
        </div>
      </div>

      {/* 구분선 */}
      <div className="border-t border-gray-200" />

      {/* 점검표 섹션 */}
      <div>
        <h4 className="text-sm font-medium text-gray-700 mb-3">점검표 옵션</h4>
        <div className="space-y-3">
          <SettingRow
            label="완료된 항목 표시"
            description="완료된 점검 항목을 목록에 표시합니다"
            checked={settings.showCompletedItems}
            onChange={() => onToggle('showCompletedItems')}
          />
          <SettingRow
            label="모든 카테고리 펼치기"
            description="점검표 카테고리를 기본으로 펼쳐서 표시합니다"
            checked={settings.expandAllCategories}
            onChange={() => onToggle('expandAllCategories')}
          />
        </div>
      </div>

      {/* 구분선 */}
      <div className="border-t border-gray-200" />

      {/* 빠른 설정 */}
      <div>
        <h4 className="text-sm font-medium text-gray-700 mb-3">빠른 설정</h4>
        <div className="grid grid-cols-2 gap-2">
          <button
            type="button"
            onClick={() => onSettingsChange({
              showProgressBar: true,
              showDocumentViewer: true,
              showDocumentSection: true,
              showCompletedItems: true,
              expandAllCategories: true,
            })}
            className="px-3 py-2 text-sm bg-blue-50 text-blue-700 rounded-lg hover:bg-blue-100 transition-colors"
          >
            모두 표시
          </button>
          <button
            type="button"
            onClick={() => onSettingsChange({
              showProgressBar: false,
              showDocumentViewer: false,
              showDocumentSection: true,
              showCompletedItems: true,
              expandAllCategories: false,
            })}
            className="px-3 py-2 text-sm bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors"
          >
            간소화
          </button>
        </div>
      </div>
    </div>
  );
}

// ===== 공통 설정 행 =====

interface SettingRowProps {
  label: string;
  description: string;
  checked: boolean;
  onChange: () => void;
}

function SettingRow({ label, description, checked, onChange }: SettingRowProps) {
  return (
    <div className="flex items-start justify-between gap-3 p-3 bg-gray-50 rounded-lg">
      <div className="flex-1">
        <div className="flex items-center gap-2">
          {checked ? (
            <Eye className="h-4 w-4 text-blue-500" />
          ) : (
            <EyeOff className="h-4 w-4 text-gray-400" />
          )}
          <span className="text-sm font-medium text-gray-800">{label}</span>
        </div>
        <p className="text-xs text-gray-500 mt-0.5 ml-6">{description}</p>
      </div>
      <Switch
        checked={checked}
        onCheckedChange={onChange}
        className="data-[state=checked]:bg-blue-500"
      />
    </div>
  );
}

// 설정 버튼 컴포넌트 (헤더에 배치용)
interface SettingsButtonProps {
  onClick: () => void;
}

export function SettingsButton({ onClick }: SettingsButtonProps) {
  return (
    <button
      type="button"
      onClick={onClick}
      className="flex items-center gap-2 px-3 sm:px-4 py-2 sm:py-2.5 text-xs sm:text-sm text-white bg-white/10 border border-white/20 rounded-lg hover:bg-white/20 transition-colors whitespace-nowrap"
    >
      <Settings className="h-4 w-4" />
      <span>화면 설정</span>
    </button>
  );
}
