"use client";

import { useState, useTransition, useEffect } from "react";

// Lightning 전역 객체 타입 선언
declare global {
  interface Window {
    $Lightning: {
      use: (appName: string, callback: () => void, salesforceUrl: string, accessToken: string) => void;
      createComponent: (componentName: string, attributes: any, container: string, callback: (cmp: any) => void) => void;
    };
  }
}
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();

  // AgentForce POC Chatbot 초기화
  useEffect(() => {
    // Lightning 스크립트 로드
    const script = document.createElement('script');
    script.src = 'https://connect-flow-8014--ps.sandbox.lightning.force.com/lightning/lightning.out.js';
    script.onload = () => {
      // 스크립트 로드 후 채팅봇 초기화
      initializeChatbot();
    };
    document.head.appendChild(script);

    return () => {
      // 컴포넌트 언마운트 시 스크립트 제거
      const existingScript = document.querySelector('script[src*="lightning.out.js"]');
      if (existingScript) {
        existingScript.remove();
      }
    };
  }, []);

  const initializeChatbot = async () => {
    try {
      const myApiUrl = 'https://pyheroku-d21d18e4f257.herokuapp.com/api/getToken';
      const salesforceUrl = 'https://connect-flow-8014--ps.sandbox.lightning.force.com/';
      const appName = 'c:zzChatBot_Aura';
      const componentContainer = 'agentforceChatbotDivId';

      const response = await fetch(myApiUrl, { method: 'POST' });
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(`백엔드 API 에러 (Status: ${response.status}): ${JSON.stringify(errorData)}`);
      }

      const data = await response.json();
      const accessToken = data.access_token;
      if (!accessToken) {
        throw new Error("응답 데이터에 access_token이 없습니다.");
      }

      console.log("백엔드를 통해 안전하게 토큰을 받았습니다:", accessToken);
      
      const lwcAttributes = {
        isDarkMode: true,
        chatbot_width: '500px',
        chatbot_height: '700px'
      };

      window.$Lightning.use(appName,
        () => {
          window.$Lightning.createComponent(
            "c:sj_Chatbot",
            lwcAttributes,
            componentContainer,
            (cmp: any) => {
              console.log('salesforce chatbot');
            }
          );
        },
        salesforceUrl,
        accessToken  
      );
    } catch (error) {
      console.error('전체 프로세스 호출 실패:', error);
    }
  };

  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">
      {/* AgentForce POC Chatbot - 우측하단 고정 */}
      <div id="agentforceChatbotDivId" className="fixed bottom-4 right-4 z-50"></div>
      {/* 헤더 */}
      <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>
  );
}