'use client';

import { useState, useMemo, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import KanbanColumn from './KanbanColumn';
import ProjectCard from './ProjectCard';
import StageCard from './StageCard';
import DetailAccordion from './DetailAccordion';
import type { ProjectDetail, Stage, DetailCategory, SelectOption } from './types';
import { getDetailCategories } from './actions';

interface ProjectKanbanBoardProps {
  projects: ProjectDetail[];
  partnerOptions?: SelectOption[];
  siteOptions?: SelectOption[];
  onProjectEndClick?: (project: ProjectDetail) => void;
}

export default function ProjectKanbanBoard({
  projects,
  partnerOptions = [],
  siteOptions = [],
  onProjectEndClick,
}: ProjectKanbanBoardProps) {
  // 필터 상태
  const [selectedPartner, setSelectedPartner] = useState<string>('all');
  const [selectedSite, setSelectedSite] = useState<string>('all');

  // 선택된 프로젝트
  const [selectedProjectId, setSelectedProjectId] = useState<string | null>(null);
  // 선택된 단계
  const [selectedStageId, setSelectedStageId] = useState<string | null>(null);
  // 상세 카테고리 (시공, 이슈 아코디언)
  const [detailCategories, setDetailCategories] = useState<DetailCategory[]>([]);
  const [isLoadingCategories, setIsLoadingCategories] = useState(false);
  // 선택된 상세 아이템
  const [selectedDetailId, setSelectedDetailId] = useState<string | null>(null);

  // 필터링된 프로젝트
  const filteredProjects = useMemo(() => {
    let result = [...projects];

    if (selectedPartner !== 'all') {
      result = result.filter((p) => p.partnerName === selectedPartner);
    }

    if (selectedSite !== 'all') {
      result = result.filter((p) => p.siteName === selectedSite);
    }

    return result;
  }, [projects, selectedPartner, selectedSite]);

  // 선택된 프로젝트 정보
  const selectedProject = useMemo(() => {
    return filteredProjects.find((p) => p.id === selectedProjectId) || null;
  }, [filteredProjects, selectedProjectId]);

  // 선택된 프로젝트의 단계 목록
  const stages = useMemo(() => {
    if (!selectedProject) return [];
    return selectedProject.stages || [];
  }, [selectedProject]);

  // 선택된 단계 정보
  const _selectedStage = useMemo(() => {
    return stages.find((s) => s.id === selectedStageId) || null;
  }, [stages, selectedStageId]);

  // 단계 선택 시 상세 카테고리 로드
  useEffect(() => {
    if (!selectedStageId) {
      setDetailCategories([]);
      return;
    }

    const loadCategories = async () => {
      setIsLoadingCategories(true);
      try {
        const result = await getDetailCategories(selectedStageId);
        if (result.success && result.data) {
          setDetailCategories(result.data);
        } else {
          setDetailCategories([]);
        }
      } catch {
        setDetailCategories([]);
      } finally {
        setIsLoadingCategories(false);
      }
    };

    loadCategories();
  }, [selectedStageId]);

  // 프로젝트 선택 핸들러
  const handleProjectClick = (project: ProjectDetail) => {
    if (selectedProjectId === project.id) {
      // 이미 선택된 프로젝트 클릭 시 선택 해제
      setSelectedProjectId(null);
      setSelectedStageId(null);
    } else {
      setSelectedProjectId(project.id);
      setSelectedStageId(null);
    }
  };

  // 단계 선택 핸들러
  const handleStageClick = (stage: Stage) => {
    if (selectedStageId === stage.id) {
      setSelectedStageId(null);
    } else {
      setSelectedStageId(stage.id);
    }
    // 단계 변경 시 상세 선택 초기화
    setSelectedDetailId(null);
  };

  // 상세 아이템 선택 핸들러
  const handleDetailSelect = (id: string) => {
    if (selectedDetailId === id) {
      setSelectedDetailId(null);
    } else {
      setSelectedDetailId(id);
    }
  };

  // 프로젝트 종료 버튼 클릭 핸들러
  const handleProjectEndClick = () => {
    if (selectedProject && onProjectEndClick) {
      onProjectEndClick(selectedProject);
    }
  };

  return (
    <div className="space-y-4">
      {/* 필터 영역 */}
      <div className="flex items-center justify-end gap-3">
        <Select value={selectedPartner} onValueChange={setSelectedPartner}>
          <SelectTrigger className="min-w-[140px] w-auto">
            <SelectValue placeholder="전체" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">전체</SelectItem>
            {partnerOptions.map((option) => (
              <SelectItem key={option.value} value={option.value}>
                {option.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>

        <Select value={selectedSite} onValueChange={setSelectedSite}>
          <SelectTrigger className="min-w-[140px] w-auto">
            <SelectValue placeholder="전체" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">전체</SelectItem>
            {siteOptions.map((option) => (
              <SelectItem key={option.value} value={option.value}>
                {option.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      {/* 칸반 보드 */}
      <div className="flex gap-4 w-full">
        {/* 프로젝트 컬럼 */}
        <KanbanColumn
          title="프로젝트"
          count={filteredProjects.length}
          isEmpty={filteredProjects.length === 0}
          emptyMessage="프로젝트가 없습니다."
        >
          {filteredProjects.map((project) => (
            <ProjectCard
              key={project.id}
              project={project}
              isSelected={selectedProjectId === project.id}
              onClick={() => handleProjectClick(project)}
            />
          ))}
        </KanbanColumn>

        {/* 단계 컬럼 */}
        <KanbanColumn
          title="단계"
          headerAction={
            selectedProject && (
              <Button
                variant="destructive"
                size="sm"
                className="h-7 text-xs"
                onClick={handleProjectEndClick}
              >
                프로젝트 종료
              </Button>
            )
          }
          isEmpty={stages.length === 0}
          emptyMessage={selectedProjectId ? '단계가 없습니다.' : '프로젝트를 선택하세요.'}
        >
          {stages.map((stage) => (
            <StageCard
              key={stage.id}
              stage={stage}
              isSelected={selectedStageId === stage.id}
              onClick={() => handleStageClick(stage)}
            />
          ))}
        </KanbanColumn>

        {/* 상세 컬럼 */}
        <KanbanColumn
          title="상세"
          isEmpty={!selectedStageId && detailCategories.length === 0}
          emptyMessage={selectedStageId ? '상세 항목이 없습니다.' : '단계를 선택하세요.'}
        >
          {isLoadingCategories ? (
            <div className="flex items-center justify-center h-24 text-sm text-muted-foreground">
              로딩 중...
            </div>
          ) : (
            <DetailAccordion
              categories={detailCategories}
              selectedDetailId={selectedDetailId}
              onDetailSelect={handleDetailSelect}
            />
          )}
        </KanbanColumn>
      </div>
    </div>
  );
}