'use client';

import React, { useState, useMemo } from 'react';
import { ChevronDown, ChevronRight, Check } from 'lucide-react';
import { cn } from '@/lib/utils';
import type { ChecklistCategory, ChecklistSubItem } from '../types';

interface Day1ChecklistPanelProps {
  categories: ChecklistCategory[];
  selectedSubItemId: string | null;
  searchTerm: string;
  onSubItemSelect: (categoryId: string, subItemId: string) => void;
  onSubItemToggle: (categoryId: string, subItemId: string, isCompleted: boolean) => void;
  isMock?: boolean;
}

export function Day1ChecklistPanel({
  categories,
  selectedSubItemId,
  searchTerm,
  onSubItemSelect,
  onSubItemToggle,
  isMock,
}: Day1ChecklistPanelProps) {
  const [expandedCategories, setExpandedCategories] = useState<Set<string>>(
    new Set(categories.map(c => c.id)) // 기본적으로 모두 펼침
  );

  // 검색 필터링된 카테고리
  const filteredCategories = useMemo(() => {
    if (!searchTerm.trim()) return categories;

    const term = searchTerm.toLowerCase();
    return categories.map(category => {
      // 카테고리 제목 매칭
      const categoryMatches = category.title.toLowerCase().includes(term);

      // 하위 항목 필터링
      const filteredSubItems = category.subItems.filter(item =>
        item.name.toLowerCase().includes(term)
      );

      // 카테고리가 매칭되면 모든 하위 항목 포함, 아니면 필터링된 항목만
      if (categoryMatches) {
        return category;
      } else if (filteredSubItems.length > 0) {
        return { ...category, subItems: filteredSubItems };
      }
      return null;
    }).filter((cat): cat is ChecklistCategory => cat !== null);
  }, [categories, searchTerm]);

  // categories 로드 완료 시 모두 펼치기
  React.useEffect(() => {
    if (categories.length > 0) {
      setExpandedCategories(new Set(categories.map(c => c.id)));
    }
  }, [categories]);

  // 검색 시 모든 카테고리 펼치기
  React.useEffect(() => {
    if (searchTerm.trim()) {
      setExpandedCategories(new Set(filteredCategories.map(c => c.id)));
    }
  }, [searchTerm, filteredCategories]);

  const toggleCategory = (categoryId: string) => {
    setExpandedCategories(prev => {
      const newSet = new Set(prev);
      if (newSet.has(categoryId)) {
        newSet.delete(categoryId);
      } else {
        newSet.add(categoryId);
      }
      return newSet;
    });
  };

  const getCategoryProgress = (category: ChecklistCategory) => {
    // 원본 카테고리에서 진행률 계산
    const originalCategory = categories.find(c => c.id === category.id);
    if (!originalCategory) return { completed: 0, total: 0 };
    const completed = originalCategory.subItems.filter(item => item.isCompleted).length;
    return { completed, total: originalCategory.subItems.length };
  };

  // 검색 결과 하이라이트
  const highlightText = (text: string, term: string) => {
    if (!term.trim()) return text;
    const regex = new RegExp(`(${term})`, 'gi');
    const parts = text.split(regex);
    return parts.map((part, index) =>
      regex.test(part) ? (
        <mark key={index} className="bg-yellow-200 text-yellow-900 px-0.5 rounded">
          {part}
        </mark>
      ) : (
        part
      )
    );
  };

  return (
    <div className="bg-white rounded-lg border border-gray-200 overflow-hidden h-full flex flex-col">
      {/* 헤더 */}
      <div className="bg-gray-100 px-2 sm:px-4 py-2 sm:py-3 border-b border-gray-200">
        <div className="flex items-center gap-2">
          <h3 className="font-semibold text-gray-900 text-sm sm:text-base">점검표 항목</h3>
          {isMock && (
            <span className="bg-amber-100 text-amber-700 text-[9px] sm:text-[10px] font-semibold px-1.5 py-0.5 rounded border border-amber-200">
              Mock
            </span>
          )}
        </div>
        {/* 검색 결과 카운트 */}
        {searchTerm && (
          <div className="mt-1.5 sm:mt-2 text-xs text-gray-500">
            {filteredCategories.length > 0
              ? `${filteredCategories.reduce((sum, cat) => sum + cat.subItems.length, 0)}개 항목 검색됨`
              : '검색 결과가 없습니다'
            }
          </div>
        )}
      </div>

      {/* 카테고리 목록 */}
      <div className="flex-1 overflow-y-auto divide-y divide-gray-200">
        {filteredCategories.length === 0 ? (
          <div className="flex items-center justify-center h-32 text-gray-400 text-sm">
            검색 결과가 없습니다
          </div>
        ) : (
          filteredCategories.map((category, _categoryIndex) => {
            const isExpanded = expandedCategories.has(category.id);
            const progress = getCategoryProgress(category);
            const allCompleted = progress.completed === progress.total;
            // 원본 인덱스 찾기
            const originalIndex = categories.findIndex(c => c.id === category.id);

            return (
              <div key={category.id}>
                {/* 카테고리 헤더 */}
                <button
                  type="button"
                  onClick={() => toggleCategory(category.id)}
                  className={cn(
                    'w-full flex items-center justify-between px-2 sm:px-4 py-2 sm:py-3 text-left transition-colors',
                    'hover:bg-gray-50',
                    allCompleted && 'bg-green-50'
                  )}
                >
                  <div className="flex items-center gap-3">
                    {isExpanded ? (
                      <ChevronDown className="h-4 w-4 text-gray-500" />
                    ) : (
                      <ChevronRight className="h-4 w-4 text-gray-500" />
                    )}
                    <span className="text-sm font-medium text-gray-800">
                      {originalIndex + 1}. {highlightText(category.title, searchTerm)}
                    </span>
                  </div>
                  <span className={cn(
                    'text-xs px-2 py-0.5 rounded-full',
                    allCompleted
                      ? 'bg-green-100 text-green-700'
                      : 'bg-gray-200 text-gray-600'
                  )}>
                    {progress.completed}/{progress.total}
                  </span>
                </button>

                {/* 하위 항목 */}
                {isExpanded && (
                  <div className="bg-gray-50 border-t border-gray-100">
                    {category.subItems.map((subItem, subIndex) => (
                      <SubItemRow
                        key={subItem.id}
                        subItem={subItem}
                        index={subIndex}
                        categoryId={category.id}
                        isSelected={selectedSubItemId === subItem.id}
                        onSelect={() => onSubItemSelect(category.id, subItem.id)}
                        onToggle={(isCompleted) => onSubItemToggle(category.id, subItem.id, isCompleted)}
                        searchTerm={searchTerm}
                        highlightText={highlightText}
                      />
                    ))}
                  </div>
                )}
              </div>
            );
          })
        )}
      </div>
    </div>
  );
}

interface SubItemRowProps {
  subItem: ChecklistSubItem;
  index: number;
  categoryId: string;
  isSelected: boolean;
  onSelect: () => void;
  onToggle: (isCompleted: boolean) => void;
  searchTerm: string;
  highlightText: (text: string, term: string) => React.ReactNode;
}

function SubItemRow({
  subItem,
  index,
  isSelected,
  onSelect,
  onToggle,
  searchTerm,
  highlightText,
}: SubItemRowProps) {
  const handleCheckboxClick = (e: React.MouseEvent) => {
    e.stopPropagation();
    onToggle(!subItem.isCompleted);
  };

  return (
    <div
      className={cn(
        'flex items-center gap-2 sm:gap-3 px-2 sm:px-4 py-2 sm:py-2.5 cursor-pointer transition-colors',
        isSelected
          ? 'bg-blue-100 border-l-4 border-blue-500'
          : 'hover:bg-gray-100 border-l-4 border-transparent',
        subItem.isCompleted && !isSelected && 'bg-green-50/50'
      )}
      onClick={onSelect}
    >
      {/* 체크박스 */}
      <button
        type="button"
        onClick={handleCheckboxClick}
        className={cn(
          'flex-shrink-0 w-5 h-5 rounded border-2 flex items-center justify-center transition-colors',
          subItem.isCompleted
            ? 'bg-green-500 border-green-500 text-white'
            : 'bg-white border-gray-300 hover:border-blue-400'
        )}
      >
        {subItem.isCompleted && <Check className="h-3 w-3" />}
      </button>

      {/* 항목 이름 */}
      <span className={cn(
        'text-sm flex-1',
        subItem.isCompleted ? 'text-gray-500' : 'text-gray-700'
      )}>
        {index + 1}. {highlightText(subItem.name, searchTerm)}
      </span>

      {/* 완료 표시 */}
      {subItem.isCompleted && (
        <span className="text-xs text-green-600 font-medium">완료</span>
      )}
    </div>
  );
}
