'use client';

import { useState, useEffect, useCallback } from 'react';
import { FolderKanban, ClipboardList, PlayCircle, CheckCircle2, Search } from 'lucide-react';
import { Input } from '@/components/ui/input';
import { Card, CardContent } from '@/components/ui/card';
import { PageLayout } from '@/components/organisms/PageLayout';
import { PageHeader } from '@/components/organisms/PageHeader';
import { DateRangeSelector } from '@/components/molecules/DateRangeSelector';
import { toast } from 'sonner';
import { format, startOfMonth, endOfMonth } from 'date-fns';
import ProjectKanbanBoard from './ProjectKanbanBoard';
import ProjectEndDialog from './ProjectEndDialog';
import type { ProjectDetail, ProjectStats, SelectOption } from './types';
import { getProjectsForKanban, getProjectStats, getPartnerOptions, getSiteOptions } from './actions';

interface ProjectDetailClientProps {
  projectId?: string;
}

export default function ProjectDetailClient({ projectId: _projectId }: ProjectDetailClientProps) {
  // 데이터 상태
  const [projects, setProjects] = useState<ProjectDetail[]>([]);
  const [stats, setStats] = useState<ProjectStats>({ total: 0, inProgress: 0, completed: 0 });
  const [partnerOptions, setPartnerOptions] = useState<SelectOption[]>([]);
  const [siteOptions, setSiteOptions] = useState<SelectOption[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  // 필터 상태
  const [filterStartDate, setFilterStartDate] = useState(() =>
    format(startOfMonth(new Date()), 'yyyy-MM-dd')
  );
  const [filterEndDate, setFilterEndDate] = useState(() =>
    format(endOfMonth(new Date()), 'yyyy-MM-dd')
  );
  const [searchQuery, setSearchQuery] = useState('');

  // 프로젝트 종료 다이얼로그 상태
  const [endDialogOpen, setEndDialogOpen] = useState(false);
  const [selectedProject, setSelectedProject] = useState<ProjectDetail | null>(null);

  // 데이터 로드
  const loadData = useCallback(async () => {
    setIsLoading(true);
    try {
      const [projectsResult, statsResult, partnersResult, sitesResult] = await Promise.all([
        getProjectsForKanban(),
        getProjectStats(),
        getPartnerOptions(),
        getSiteOptions(),
      ]);

      if (projectsResult.success && projectsResult.data) {
        setProjects(projectsResult.data);
      }
      if (statsResult.success && statsResult.data) {
        setStats(statsResult.data);
      }
      if (partnersResult.success && partnersResult.data) {
        setPartnerOptions(partnersResult.data);
      }
      if (sitesResult.success && sitesResult.data) {
        setSiteOptions(sitesResult.data);
      }
    } catch {
      toast.error('데이터 로드에 실패했습니다.');
    } finally {
      setIsLoading(false);
    }
  }, []);

  useEffect(() => {
    loadData();
  }, [loadData]);

  // 검색 필터링된 프로젝트
  const filteredProjects = projects.filter((project) => {
    if (!searchQuery) return true;
    const query = searchQuery.toLowerCase();
    return (
      project.siteName.toLowerCase().includes(query) ||
      project.partnerName.toLowerCase().includes(query) ||
      project.contractNumber.toLowerCase().includes(query)
    );
  });

  // 프로젝트 종료 버튼 클릭 핸들러
  const handleProjectEndClick = (project: ProjectDetail) => {
    setSelectedProject(project);
    setEndDialogOpen(true);
  };

  // 프로젝트 종료 성공 핸들러
  const handleEndSuccess = () => {
    loadData();
  };

  return (
    <PageLayout>
      {/* 페이지 헤더 */}
      <PageHeader
        title="프로젝트 실행 관리"
        description="프로젝트 실행 관리(제안서)"
        icon={FolderKanban}
      />

      {/* 기간 선택 + 검색 영역 */}
      <DateRangeSelector
        startDate={filterStartDate}
        endDate={filterEndDate}
        onStartDateChange={setFilterStartDate}
        onEndDateChange={setFilterEndDate}
        extraActions={
          <div className="relative w-full sm:w-[300px]">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
            <Input
              placeholder="프로젝트 검색 (현장명, 거래처, 계약번호)"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-10"
            />
          </div>
        }
      />

      {/* 상태 카드 */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center gap-3">
              <div className="p-2 bg-blue-100 rounded-lg">
                <ClipboardList className="h-5 w-5 text-blue-600" />
              </div>
              <div>
                <p className="text-sm text-muted-foreground">전체 프로젝트</p>
                <p className="text-2xl font-bold">{stats.total}</p>
              </div>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center gap-3">
              <div className="p-2 bg-green-100 rounded-lg">
                <PlayCircle className="h-5 w-5 text-green-600" />
              </div>
              <div>
                <p className="text-sm text-muted-foreground">프로젝트 진행</p>
                <p className="text-2xl font-bold">{stats.inProgress}</p>
              </div>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center gap-3">
              <div className="p-2 bg-gray-100 rounded-lg">
                <CheckCircle2 className="h-5 w-5 text-gray-600" />
              </div>
              <div>
                <p className="text-sm text-muted-foreground">프로젝트 완료</p>
                <p className="text-2xl font-bold">{stats.completed}</p>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* 칸반 보드 */}
      <Card>
        <CardContent className="p-4 min-h-[600px]">
          {isLoading ? (
            <div className="flex items-center justify-center h-[500px]">
              <p className="text-muted-foreground">로딩 중...</p>
            </div>
          ) : (
            <ProjectKanbanBoard
              projects={filteredProjects}
              partnerOptions={partnerOptions}
              siteOptions={siteOptions}
              onProjectEndClick={handleProjectEndClick}
            />
          )}
        </CardContent>
      </Card>

      {/* 프로젝트 종료 다이얼로그 */}
      <ProjectEndDialog
        open={endDialogOpen}
        onOpenChange={setEndDialogOpen}
        project={selectedProject}
        onSuccess={handleEndSuccess}
      />
    </PageLayout>
  );
}
