"use client";

import { useState, useTransition } from "react";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Button } from "@/components/ui/button";
import { RefreshCw } from "lucide-react";
import { DashboardStatsCard } from "./dashboard-stats-card";
import { DashboardOverviewChart } from "./dashboard-overview-chart";
import { DashboardSummaryCards } from "./dashboard-summary-cards";
import { toast } from "sonner";
import { DashboardData, getDashboardData } from "./service";

interface DashboardClientProps {
  initialData: DashboardData;
}

export function DashboardClient({ initialData }: DashboardClientProps) {


  const [data, setData] = useState<DashboardData>(initialData);
  const [isPending, startTransition] = useTransition();


  console.log(data)

  const { domain, teamStats, userStats, summary } = data;

  const getDomainDisplayName = (domain: string) => {
    const domainNames: Record<string, string> = {
      'procurement': '구매 관리',
      'sales': '영업 관리',
      "partners": 'Partners',
      'engineering': '엔지니어링'
    };
    return domainNames[domain] || domain;
  };

  const handleRefresh = () => {
    startTransition(async () => {
      try {
        const refreshedData = await getDashboardData(domain);
        setData(refreshedData);
        toast.success("데이터가 새로고침되었습니다.");
      } catch (error) {
        console.error("Refresh failed:", error);
        toast.error("데이터 새로고침에 실패했습니다.");
      }
    });
  };

  // 데이터가 없으면 에러 상태 표시
  if (!summary) {
    return (
      <div className="flex items-center justify-center py-12">
        <div className="text-center space-y-2">
          <p className="text-destructive">데이터를 불러올 수 없습니다.</p>
          <Button onClick={handleRefresh} variant="outline" size="sm">
            다시 시도
          </Button>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* 헤더 */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold tracking-tight">
            {getDomainDisplayName(domain)} 대시보드 
          </h2>
          {/* <p className="text-muted-foreground">
            {domain === "partners"
              ? "회사와 개인에게 할당된 일들을 보여줍니다."
              : "팀과 개인에게 할당된 일들을 보여줍니다."
            }
          </p> */}
        </div>
        <Button 
          onClick={handleRefresh} 
          variant="outline" 
          size="sm"
          disabled={isPending}
        >
          <RefreshCw className={`h-4 w-4 mr-2 ${isPending ? 'animate-spin' : ''}`} />
          새로고침
        </Button>
      </div>

      {/* 요약 카드 */}
      <DashboardSummaryCards summary={summary} />

      {/* 차트 */}
      <DashboardOverviewChart 
        data={teamStats}
        title={getDomainDisplayName(domain)}
        description="업무 타입별 현황을 확인하세요"
      />

      {/* 탭 */}
      <Tabs defaultValue="team" className="space-y-4">
        <TabsList className="grid w-full grid-cols-2 max-w-md">
          <TabsTrigger value="team">
            {domain === "partners" ? "회사 업무 현황" : "팀 업무 현황"}
          </TabsTrigger>
          <TabsTrigger value="personal">내 업무 현황</TabsTrigger>
        </TabsList>

        <TabsContent value="team" className="space-y-4">
          <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
            {teamStats.map((stats) => (
              <DashboardStatsCard
                key={stats.tableName}
                stats={stats}
                showUserStats={false}
              />
            ))}
          </div>
        </TabsContent>

        <TabsContent value="personal" className="space-y-4">
          <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
            {userStats.map((stats) => (
              <DashboardStatsCard
                key={stats.tableName}
                stats={stats}
                showUserStats={true}
              />
            ))}
          </div>
        </TabsContent>
      </Tabs>
    </div>
  );
}