"use client"

import * as React from "react"
import { Shell } from "@/components/shell"
import { Skeleton } from "@/components/ui/skeleton"
import { PQInputTabs } from "@/components/pq/pq-input-tabs"
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { PQGroupData, ProjectPQ } from "@/lib/pq/service"
import { useRouter, useSearchParams } from "next/navigation"

interface ClientPQWrapperProps {
  allPQData: PQGroupData[]
  projectPQs: ProjectPQ[]
  vendorId: number
  rawSearchParams: {
    projectId?: string
  }
}

export function ClientPQWrapper({
  allPQData,
  projectPQs,
  vendorId,
  rawSearchParams
}: ClientPQWrapperProps) {
  const searchParams = useSearchParams()
  const projectIdParam = searchParams?.get('projectId')
  
  // 클라이언트 측에서 projectId 파싱
  const projectId = projectIdParam ? parseInt(projectIdParam, 10) : undefined
  
  // 현재 프로젝트 정보 찾기
  const currentProject = projectId
    ? projectPQs.find(p => p.projectId === projectId)
    : null
    
  // 필요한 경우 여기서 PQ 데이터를 필터링할 수 있음
  // 예: 모든 데이터를 가져왔는데 현재 projectId에 따라 필터링이 필요한 경우
  // const filteredPQData = projectId ? allPQData.filter(...) : allPQData;

  return (
    <Shell className="gap-2">
      {/* 헤더 - 프로젝트 정보 포함 */}
      <div className="space-y-2">
        <h2 className="text-2xl font-bold tracking-tight">
          Pre-Qualification Check Sheet
          {currentProject && (
            <span className="ml-2 text-muted-foreground">
              - {currentProject.projectCode}
            </span>
          )}
        </h2>
        <p className="text-muted-foreground">
          PQ에 적절한 응답을 제출하시기 바랍니다.
        </p>
      </div>

      {/* 일반/프로젝트 PQ 선택 탭 */}
      {projectPQs.length > 0 && (
        <div className="border-b">
          <Tabs defaultValue={projectId ? `project-${projectId}` : "general"}>
            <TabsList>
              <TabsTrigger value="general" asChild>
                <a href="/partners/pq">일반 PQ</a>
              </TabsTrigger>
              
              {projectPQs.map(project => (
                <TabsTrigger key={project.projectId} value={`project-${project.projectId}`} asChild>
                  <a href={`/partners/pq?projectId=${project.projectId}`}>
                    {project.projectCode}
                  </a>
                </TabsTrigger>
              ))}
            </TabsList>
          </Tabs>
        </div>
      )}

      {/* PQ 입력 탭 */}
      <React.Suspense fallback={<Skeleton className="h-7 w-52" />}>
        <PQInputTabs
          data={allPQData}
          vendorId={vendorId}
          projectId={projectId}
          projectData={currentProject}
        />
      </React.Suspense>
    </Shell>
  )
}