'use client';

import { useState, useCallback, useEffect, useMemo } from 'react';
import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog';
import { cn } from '@/lib/utils';
import type {
  DashboardSettings,
  TodayIssueSettings,
  EntertainmentLimitType,
  CompanyType,
  WelfareLimitType,
  WelfareCalculationType,
  SectionKey,
} from '../types';
import { DEFAULT_SECTION_ORDER, SECTION_LABELS, sectionRequiresModule } from '../types';
import { useModules } from '@/hooks/useModules';
import {
  SectionRow,
  StatusBoardItemsList,
  EntertainmentContent,
  WelfareContent,
} from './DashboardSettingsSections';

interface DashboardSettingsDialogProps {
  isOpen: boolean;
  onClose: () => void;
  settings: DashboardSettings;
  onSave: (settings: DashboardSettings) => void;
}

export function DashboardSettingsDialog({
  isOpen,
  onClose,
  settings,
  onSave,
}: DashboardSettingsDialogProps) {
  // 모듈 활성화 정보 (industry 미설정 시 전부 표시)
  const { isEnabled, tenantIndustry } = useModules();
  const moduleAware = !!tenantIndustry;

  const [localSettings, setLocalSettings] = useState<DashboardSettings>(settings);
  const [expandedSections, setExpandedSections] = useState<Record<string, boolean>>({
    todayIssueList: false,
    entertainment: false,
    welfare: false,
    statusBoard: false,
    companyTypeInfo: false,
  });

  // DnD 상태
  const [draggedSection, setDraggedSection] = useState<SectionKey | null>(null);
  const [dragOverSection, setDragOverSection] = useState<SectionKey | null>(null);

  // 섹션 순서 (모듈 비활성 섹션 숨김)
  const sectionOrder = useMemo<SectionKey[]>(() => {
    const rawOrder = localSettings.sectionOrder ?? DEFAULT_SECTION_ORDER;
    if (!moduleAware) return rawOrder;
    return rawOrder.filter((key: SectionKey) => {
      const requiredModule = sectionRequiresModule(key);
      if (!requiredModule) return true;
      return isEnabled(requiredModule);
    });
  }, [localSettings.sectionOrder, moduleAware, isEnabled]);

  // settings가 변경될 때 로컬 상태 업데이트
  useEffect(() => {
    setLocalSettings(settings);
  }, [settings]);

  // 섹션 펼침/접힘 토글
  const toggleSection = useCallback((section: string) => {
    setExpandedSections((prev) => ({
      ...prev,
      [section]: !prev[section],
    }));
  }, []);

  // 오늘의 이슈 (리스트 형태) 토글
  const handleTodayIssueListToggle = useCallback((enabled: boolean) => {
    setLocalSettings((prev) => ({
      ...prev,
      todayIssueList: enabled,
    }));
  }, []);

  // 현황판 전체 토글 (구 오늘의 이슈)
  const handleStatusBoardToggle = useCallback((enabled: boolean) => {
    setLocalSettings((prev) => {
      const statusBoardItems = prev.statusBoard?.items ?? prev.todayIssue.items;
      return {
        ...prev,
        statusBoard: {
          enabled,
          items: enabled
            ? statusBoardItems
            : Object.keys(statusBoardItems).reduce(
                (acc, key) => ({ ...acc, [key]: false }),
                {} as TodayIssueSettings
              ),
        },
        todayIssue: {
          enabled,
          items: enabled
            ? statusBoardItems
            : Object.keys(statusBoardItems).reduce(
                (acc, key) => ({ ...acc, [key]: false }),
                {} as TodayIssueSettings
              ),
        },
      };
    });
  }, []);

  // 현황판 개별 항목 토글
  const handleStatusBoardItemToggle = useCallback(
    (key: keyof TodayIssueSettings, enabled: boolean) => {
      setLocalSettings((prev) => {
        const statusBoardItems = prev.statusBoard?.items ?? prev.todayIssue.items;
        const newItems = {
          ...statusBoardItems,
          [key]: enabled,
        };
        return {
          ...prev,
          statusBoard: {
            ...prev.statusBoard,
            enabled: prev.statusBoard?.enabled ?? prev.todayIssue.enabled,
            items: newItems,
          },
          todayIssue: {
            ...prev.todayIssue,
            items: newItems,
          },
        };
      });
    },
    []
  );

  // 메인 섹션 토글
  const handleSectionToggle = useCallback(
    (
      section:
        | 'dailyReport'
        | 'monthlyExpense'
        | 'cardManagement'
        | 'debtCollection'
        | 'vat'
        | 'calendar'
        | 'production'
        | 'shipment'
        | 'unshipped'
        | 'construction'
        | 'attendance',
      enabled: boolean
    ) => {
      setLocalSettings((prev) => ({
        ...prev,
        [section]: enabled,
      }));
    },
    []
  );

  // 매출/매입/미수금 현황 토글 (단순 boolean)
  const handleSimpleSectionToggle = useCallback(
    (section: 'salesStatus' | 'purchaseStatus' | 'receivable', enabled: boolean) => {
      setLocalSettings((prev) => ({
        ...prev,
        [section]: enabled,
      }));
    },
    []
  );

  // 접대비 설정 변경
  const handleEntertainmentChange = useCallback(
    (
      key: 'enabled' | 'limitType' | 'companyType' | 'highAmountThreshold',
      value: boolean | EntertainmentLimitType | CompanyType | number
    ) => {
      setLocalSettings((prev) => ({
        ...prev,
        entertainment: {
          ...prev.entertainment,
          [key]: value,
        },
      }));
    },
    []
  );

  // 복리후생비 설정 변경
  const handleWelfareChange = useCallback(
    (
      key: keyof typeof localSettings.welfare,
      value: boolean | WelfareLimitType | WelfareCalculationType | number
    ) => {
      setLocalSettings((prev) => ({
        ...prev,
        welfare: {
          ...prev.welfare,
          [key]: value,
        },
      }));
    },
    []
  );

  // 섹션 순서 변경 (DnD)
  const handleReorder = useCallback((sourceKey: SectionKey, targetKey: SectionKey) => {
    setLocalSettings((prev) => {
      const order = [...(prev.sectionOrder ?? DEFAULT_SECTION_ORDER)];
      const sourceIdx = order.indexOf(sourceKey);
      const targetIdx = order.indexOf(targetKey);
      if (sourceIdx === -1 || targetIdx === -1) return prev;
      order.splice(sourceIdx, 1);
      order.splice(targetIdx, 0, sourceKey);
      return { ...prev, sectionOrder: order };
    });
  }, []);

  // 저장
  const handleSave = useCallback(() => {
    onSave(localSettings);
    onClose();
  }, [localSettings, onSave, onClose]);

  // 취소
  const handleCancel = useCallback(() => {
    setLocalSettings(settings);
    onClose();
  }, [settings, onClose]);

  // 섹션 렌더링 함수
  const renderSection = (key: SectionKey): React.ReactNode => {
    switch (key) {
      case 'todayIssueList':
        return (
          <SectionRow
            label={SECTION_LABELS.todayIssueList}
            checked={localSettings.todayIssueList}
            onCheckedChange={handleTodayIssueListToggle}
            hasExpand
            isExpanded={expandedSections.todayIssueList}
            onToggleExpand={() => toggleSection('todayIssueList')}
            showGrip
          >
            <StatusBoardItemsList
              items={localSettings.statusBoard?.items ?? localSettings.todayIssue.items}
              onToggle={handleStatusBoardItemToggle}
            />
          </SectionRow>
        );

      case 'dailyReport':
        return (
          <SectionRow
            label={SECTION_LABELS.dailyReport}
            checked={localSettings.dailyReport}
            onCheckedChange={(checked) => handleSectionToggle('dailyReport', checked)}
            showGrip
          />
        );

      case 'statusBoard':
        return (
          <SectionRow
            label={SECTION_LABELS.statusBoard}
            checked={localSettings.statusBoard?.enabled ?? localSettings.todayIssue.enabled}
            onCheckedChange={handleStatusBoardToggle}
            hasExpand
            isExpanded={expandedSections.statusBoard}
            onToggleExpand={() => toggleSection('statusBoard')}
            showGrip
          >
            <StatusBoardItemsList
              items={localSettings.statusBoard?.items ?? localSettings.todayIssue.items}
              onToggle={handleStatusBoardItemToggle}
            />
          </SectionRow>
        );

      case 'monthlyExpense':
        return (
          <SectionRow
            label={SECTION_LABELS.monthlyExpense}
            checked={localSettings.monthlyExpense}
            onCheckedChange={(checked) => handleSectionToggle('monthlyExpense', checked)}
            showGrip
          />
        );

      case 'cardManagement':
        return (
          <SectionRow
            label={SECTION_LABELS.cardManagement}
            checked={localSettings.cardManagement}
            onCheckedChange={(checked) => handleSectionToggle('cardManagement', checked)}
            showGrip
          />
        );

      case 'entertainment':
        return (
          <SectionRow
            label={SECTION_LABELS.entertainment}
            checked={localSettings.entertainment.enabled}
            onCheckedChange={(checked) => handleEntertainmentChange('enabled', checked)}
            hasExpand
            isExpanded={expandedSections.entertainment}
            onToggleExpand={() => toggleSection('entertainment')}
            showGrip
          >
            <EntertainmentContent
              entertainment={localSettings.entertainment}
              onChange={handleEntertainmentChange}
              companyTypeInfoExpanded={expandedSections.companyTypeInfo}
              onToggleCompanyTypeInfo={() => toggleSection('companyTypeInfo')}
            />
          </SectionRow>
        );

      case 'welfare':
        return (
          <SectionRow
            label={SECTION_LABELS.welfare}
            checked={localSettings.welfare.enabled}
            onCheckedChange={(checked) => handleWelfareChange('enabled', checked)}
            hasExpand
            isExpanded={expandedSections.welfare}
            onToggleExpand={() => toggleSection('welfare')}
            showGrip
          >
            <WelfareContent
              welfare={localSettings.welfare}
              onChange={handleWelfareChange}
            />
          </SectionRow>
        );

      case 'receivable':
        return (
          <SectionRow
            label={SECTION_LABELS.receivable}
            checked={localSettings.receivable ?? true}
            onCheckedChange={(checked) => handleSimpleSectionToggle('receivable', checked)}
            showGrip
          />
        );

      case 'debtCollection':
        return (
          <SectionRow
            label={SECTION_LABELS.debtCollection}
            checked={localSettings.debtCollection}
            onCheckedChange={(checked) => handleSectionToggle('debtCollection', checked)}
            showGrip
          />
        );

      case 'vat':
        return (
          <SectionRow
            label={SECTION_LABELS.vat}
            checked={localSettings.vat}
            onCheckedChange={(checked) => handleSectionToggle('vat', checked)}
            showGrip
          />
        );

      case 'calendar':
        return (
          <SectionRow
            label={SECTION_LABELS.calendar}
            checked={localSettings.calendar}
            onCheckedChange={(checked) => handleSectionToggle('calendar', checked)}
            showGrip
          />
        );

      case 'salesStatus':
        return (
          <SectionRow
            label={SECTION_LABELS.salesStatus}
            checked={localSettings.salesStatus ?? true}
            onCheckedChange={(checked) => handleSimpleSectionToggle('salesStatus', checked)}
            showGrip
          />
        );

      case 'purchaseStatus':
        return (
          <SectionRow
            label={SECTION_LABELS.purchaseStatus}
            checked={localSettings.purchaseStatus ?? true}
            onCheckedChange={(checked) => handleSimpleSectionToggle('purchaseStatus', checked)}
            showGrip
          />
        );

      case 'production':
        return (
          <SectionRow
            label={SECTION_LABELS.production}
            checked={localSettings.production ?? true}
            onCheckedChange={(checked) => handleSectionToggle('production', checked)}
            showGrip
          />
        );

      case 'shipment':
        return (
          <SectionRow
            label={SECTION_LABELS.shipment}
            checked={localSettings.shipment ?? true}
            onCheckedChange={(checked) => handleSectionToggle('shipment', checked)}
            showGrip
          />
        );

      case 'unshipped':
        return (
          <SectionRow
            label={SECTION_LABELS.unshipped}
            checked={localSettings.unshipped ?? true}
            onCheckedChange={(checked) => handleSectionToggle('unshipped', checked)}
            showGrip
          />
        );

      case 'construction':
        return (
          <SectionRow
            label={SECTION_LABELS.construction}
            checked={localSettings.construction ?? true}
            onCheckedChange={(checked) => handleSectionToggle('construction', checked)}
            showGrip
          />
        );

      case 'attendance':
        return (
          <SectionRow
            label={SECTION_LABELS.attendance}
            checked={localSettings.attendance ?? true}
            onCheckedChange={(checked) => handleSectionToggle('attendance', checked)}
            showGrip
          />
        );

      default:
        return null;
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={(open) => !open && handleCancel()}>
      <DialogContent className="w-[95vw] max-w-[450px] sm:max-w-[450px] max-h-[85vh] overflow-y-auto bg-white border-gray-200 p-0">
        <DialogHeader className="p-4 border-b border-gray-200">
          <DialogTitle className="text-lg font-bold text-gray-900">항목 설정</DialogTitle>
        </DialogHeader>

        <div className="space-y-3 p-4">
          {sectionOrder.map((key) => (
            <div
              key={key}
              draggable
              onDragStart={(e) => {
                e.dataTransfer.effectAllowed = 'move';
                e.dataTransfer.setData(
                  'application/json',
                  JSON.stringify({ type: 'dashboard-section', key })
                );
                setDraggedSection(key);
              }}
              onDragEnd={() => {
                setDraggedSection(null);
                setDragOverSection(null);
              }}
              onDragOver={(e) => {
                e.preventDefault();
                e.dataTransfer.dropEffect = 'move';
                if (key !== draggedSection) {
                  setDragOverSection(key);
                }
              }}
              onDragLeave={() => setDragOverSection(null)}
              onDrop={(e) => {
                e.preventDefault();
                try {
                  const data = JSON.parse(e.dataTransfer.getData('application/json'));
                  if (data.type !== 'dashboard-section') return;
                  const sourceKey = data.key as SectionKey;
                  if (sourceKey !== key) handleReorder(sourceKey, key);
                } catch {
                  // ignore
                }
                setDraggedSection(null);
                setDragOverSection(null);
              }}
              className={cn(
                'transition-all',
                draggedSection === key && 'opacity-50',
                dragOverSection === key && draggedSection !== key && 'border-t-2 border-blue-500'
              )}
            >
              {renderSection(key)}
            </div>
          ))}
        </div>

        <DialogFooter className="flex flex-row gap-3 p-4 border-t border-gray-200 justify-center">
          <Button
            variant="outline"
            onClick={handleCancel}
            className="w-20 bg-gray-100 hover:bg-gray-200 text-gray-700 border-gray-300 rounded-full"
          >
            취소
          </Button>
          <Button
            onClick={handleSave}
            className="w-20 bg-gray-500 hover:bg-gray-600 text-white rounded-full"
          >
            저장
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
