"use client";

import { useEffect } from "react";
import { useParams } from "next/navigation";
import { AlertTriangle, RefreshCw } from "lucide-react";
import { useShallow } from "zustand/react/shallow";
import { Canvas } from "@/components/canvas/Canvas";
import { ScriptWorkspace } from "@/components/project/ScriptWorkspace";
import { DefaultService } from "@lib/api";
import { useProjectStore } from "@lib/store/project";
import { useProjectWorkspace } from "@/lib/hooks/useProjects";
import { LoadingState } from "@/components/ui/loading-state";
import { Button } from "@/components/ui/button";
import { CanvasErrorBoundary } from "@/components/common/ErrorBoundary";
import { ProtectedRoute } from "@/components/auth/ProtectedRoute";

function ProjectContent() {
  const params = useParams();
  const projectId = (params?.id as string) ?? null;

  const setProject = useProjectStore((s) => s.setProject);
  const updateProjectMeta = useProjectStore((s) => s.updateProjectMeta);
  const { assets, updateAsset, updateStoryboard } = useProjectStore(
    useShallow((s) => ({
      assets: s.assets,
      updateAsset: s.updateAsset,
      updateStoryboard: s.updateStoryboard,
    })),
  );

  const { data, isLoading, error, refetch } = useProjectWorkspace(projectId);
  const project = ((data as any)?.data?.data ?? (data as any)?.data) || null;

  useEffect(() => {
    if (projectId) {
      updateProjectMeta({ id: projectId });
    }
  }, [projectId, updateProjectMeta]);

  useEffect(() => {
    if (project) {
      setProject(project);
    }
  }, [project, setProject]);

  const handleUpdateAsset = async (id: string, updates: Record<string, unknown>) => {
    const previousAsset = assets.find((a) => a.id === id);
    updateAsset(id, updates);
    try {
      await DefaultService.updateAsset(projectId, id, updates);
    } catch (e) {
      if (previousAsset) {
        updateAsset(id, previousAsset);
      }
      throw e;
    }
  };

  const handleUpdateStoryboard = async (id: string, updates: Record<string, unknown>) => {
    updateStoryboard(id, updates);
    try {
      await DefaultService.updateStoryboard(projectId, id, updates);
    } catch {
      // 可在此做乐观回滚
    }
  };

  if (!projectId) {
    return (
      <div className="flex h-screen w-screen items-center justify-center bg-background">
        <LoadingState message="无效的项目" />
      </div>
    );
  }

  if (isLoading && !data) {
    return (
      <div className="flex h-screen w-screen items-center justify-center bg-background">
        <LoadingState message="加载项目中..." />
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex h-screen w-screen flex-col items-center justify-center gap-4 bg-background px-4">
        <div className="flex flex-col items-center gap-3 text-center">
          <div className="rounded-full bg-destructive/10 p-3">
            <AlertTriangle className="h-10 w-10 text-destructive" />
          </div>
          <h2 className="text-lg font-medium">加载项目失败</h2>
          <p className="max-w-sm text-sm text-muted-foreground">
            {error instanceof Error ? error.message : "请稍后重试"}
          </p>
        </div>
        <Button variant="outline" onClick={() => refetch()} className="gap-2">
          <RefreshCw className="h-4 w-4" />
          重试
        </Button>
      </div>
    );
  }

  return (
    <div className="flex h-screen w-screen flex-col overflow-hidden bg-background">
      {project?.type === 'script' ? (
        <ScriptWorkspace
          project={project}
          onProjectChange={() => {
            refetch();
          }}
          onRefetch={() => {
            refetch();
          }}
        />
      ) : (
        <div className="relative flex-1 w-full overflow-hidden">
          <CanvasErrorBoundary>
            <Canvas
              onUpdateAsset={handleUpdateAsset}
              onUpdateStoryboard={handleUpdateStoryboard}
            />
          </CanvasErrorBoundary>
        </div>
      )}
    </div>
  );
}

export default function ProjectWorkspace() {
  return (
    <ProtectedRoute>
      <ProjectContent />
    </ProtectedRoute>
  );
}
