'use client';

import { useState } from 'react';
import { ChevronUp, ChevronDown } from 'lucide-react';
import { cn } from '@/lib/utils';
import { Badge } from '@/components/ui/badge';
import type {
  DetailCategory,
  ConstructionItem,
  IssueItem,
} from './types';
import {
  DETAIL_CATEGORY_LABELS,
  CONSTRUCTION_STATUS_LABELS,
  ISSUE_STATUS_LABELS,
} from './types';

interface DetailAccordionProps {
  categories: DetailCategory[];
  selectedDetailId?: string | null;
  onDetailSelect?: (id: string) => void;
}

export default function DetailAccordion({
  categories,
  selectedDetailId,
  onDetailSelect
}: DetailAccordionProps) {
  // 첫 번째 카테고리만 기본 열림
  const [openCategories, setOpenCategories] = useState<string[]>(
    categories.length > 0 ? [categories[0].type] : []
  );

  const toggleCategory = (type: string) => {
    setOpenCategories((prev) =>
      prev.includes(type) ? prev.filter((t) => t !== type) : [...prev, type]
    );
  };

  if (categories.length === 0) {
    return (
      <div className="flex items-center justify-center h-24 text-sm text-muted-foreground">
        상세 정보가 없습니다.
      </div>
    );
  }

  return (
    <div className="space-y-3">
      {categories.map((category) => (
        <CategoryAccordionItem
          key={category.type}
          category={category}
          isOpen={openCategories.includes(category.type)}
          onToggle={() => toggleCategory(category.type)}
          selectedDetailId={selectedDetailId}
          onDetailSelect={onDetailSelect}
        />
      ))}
    </div>
  );
}

interface CategoryAccordionItemProps {
  category: DetailCategory;
  isOpen: boolean;
  onToggle: () => void;
  selectedDetailId?: string | null;
  onDetailSelect?: (id: string) => void;
}

function CategoryAccordionItem({
  category,
  isOpen,
  onToggle,
  selectedDetailId,
  onDetailSelect,
}: CategoryAccordionItemProps) {
  const label = DETAIL_CATEGORY_LABELS[category.type];

  return (
    <div className="border rounded-lg overflow-hidden bg-card">
      {/* 아코디언 헤더 */}
      <button
        type="button"
        onClick={onToggle}
        className="w-full flex items-center justify-between p-3 hover:bg-muted/50 transition-colors"
      >
        <div>
          <h4 className="text-sm font-semibold text-foreground">{label}</h4>
          <p className="text-xs text-muted-foreground">{category.count}건</p>
        </div>
        {isOpen ? (
          <ChevronUp className="h-4 w-4 text-muted-foreground" />
        ) : (
          <ChevronDown className="h-4 w-4 text-muted-foreground" />
        )}
      </button>

      {/* 아코디언 컨텐츠 */}
      {isOpen && (
        <div className="border-t p-2 space-y-2 bg-muted/30 max-h-[300px] overflow-y-auto">
          {category.type === 'construction' &&
            category.constructionItems?.map((item) => (
              <ConstructionCard
                key={item.id}
                item={item}
                isSelected={selectedDetailId === item.id}
                onClick={() => onDetailSelect?.(item.id)}
              />
            ))}
          {category.type === 'issue' &&
            category.issueItems?.map((item) => (
              <IssueCard
                key={item.id}
                item={item}
                isSelected={selectedDetailId === item.id}
                onClick={() => onDetailSelect?.(item.id)}
              />
            ))}
        </div>
      )}
    </div>
  );
}

interface ConstructionCardProps {
  item: ConstructionItem;
  isSelected?: boolean;
  onClick?: () => void;
}

function ConstructionCard({ item, isSelected, onClick }: ConstructionCardProps) {
  const statusLabel = CONSTRUCTION_STATUS_LABELS[item.status];
  const isInProgress = item.status === 'in_progress';

  return (
    <div
      className={cn(
        'bg-card rounded-lg p-3 border cursor-pointer transition-all hover:shadow-md',
        isSelected && 'ring-2 ring-primary border-primary'
      )}
      onClick={onClick}
    >
      <div className="flex items-center justify-between gap-2">
        <div className="min-w-0 flex-1">
          <p className="text-sm font-medium text-foreground">{item.number}</p>
          <p className="text-xs text-muted-foreground">
            시공투입일: {item.inputDate}
          </p>
        </div>
        <Badge
          variant={isInProgress ? 'default' : 'secondary'}
          className={cn(
            'text-xs shrink-0',
            isInProgress && 'bg-blue-500 hover:bg-blue-600'
          )}
        >
          {statusLabel}
        </Badge>
      </div>
    </div>
  );
}

interface IssueCardProps {
  item: IssueItem;
  isSelected?: boolean;
  onClick?: () => void;
}

function IssueCard({ item, isSelected, onClick }: IssueCardProps) {
  const statusLabel = ISSUE_STATUS_LABELS[item.status];
  const isOpen = item.status === 'open';

  return (
    <div
      className={cn(
        'bg-card rounded-lg p-3 border cursor-pointer transition-all hover:shadow-md',
        isSelected && 'ring-2 ring-primary border-primary'
      )}
      onClick={onClick}
    >
      <div className="flex items-center justify-between gap-2">
        <div className="min-w-0 flex-1">
          <p className="text-sm font-medium text-foreground">{item.number}</p>
          <p className="text-xs text-muted-foreground">{item.title}</p>
        </div>
        <Badge
          variant={isOpen ? 'destructive' : 'secondary'}
          className="text-xs shrink-0"
        >
          {statusLabel}
        </Badge>
      </div>
    </div>
  );
}
