import { createClient } from '@/lib/supabase/server'
import Link from 'next/link'
import FlowchartEditor from './FlowchartEditor'
import type { FlowchartData } from '@/types/flowchart'

type PageProps = {
  params: Promise<{ projectId: string }>
}

export default async function EditorPage({ params }: PageProps) {
  const { projectId } = await params
  const supabase = await createClient()

  const {
    data: { user },
  } = await supabase.auth.getUser()

  if (!user) {
    return null
  }

  const { data: project, error } = await supabase
    .from('projects')
    .select('id, name, flowchart_data')
    .eq('id', projectId)
    .eq('user_id', user.id)
    .single()

  if (error || !project) {
    notFound()
  }

  const rawData = project.flowchart_data || {}
  const flowchartData: FlowchartData = {
    nodes: rawData.nodes || [],
    edges: rawData.edges || [],
    characters: rawData.characters || [],
    variables: rawData.variables || [],
  }

  // Migration flag: if the raw data doesn't have characters/variables arrays,
  // the project was created before these features existed and may need auto-migration
  const needsMigration = !rawData.characters && !rawData.variables

  return (<>
    <div className="flex h-screen flex-col">
      <header className="flex items-center justify-between border-b border-zinc-200 bg-white px-4 py-3 dark:border-zinc-700 dark:bg-zinc-900">
        <div className="flex items-center gap-4">
          <Link
            href="/dashboard"
            className="text-zinc-600 hover:text-zinc-900 dark:text-zinc-400 dark:hover:text-zinc-50"
            aria-label="Back to dashboard"
          >
            <svg
              xmlns="http://www.w3.org/2000/svg"
              className="h-5 w-5"
              viewBox="0 0 20 20"
              fill="currentColor"
            >
              <path
                fillRule="evenodd"
                d="M9.707 16.707a1 1 0 01-1.414 0l-6-6a1 1 0 010-1.414l6-6a1 1 0 011.414 1.414L5.414 9H17a1 1 0 110 2H5.414l4.293 4.293a1 1 0 010 1.414z"
                clipRule="evenodd"
              />
            </svg>
          </Link>
        </header>
        <div className="flex flex-1 items-center justify-center bg-zinc-100 dark:bg-zinc-800">
          <div className="flex flex-col items-center gap-4 text-center">
            <svg
              className="h-12 w-12 text-red-400"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={1.5}
                d="M12 9v3.75m9-.75a9 9 0 11-18 0 9 9 0 0118 0zm-9 3.75h.008v.008H12v-.008z"
              />
            </svg>
            <h2 className="text-lg font-semibold text-zinc-900 dark:text-zinc-50">
              Project Not Found
            </h2>
            <p className="max-w-sm text-sm text-zinc-600 dark:text-zinc-400">
              The project you&apos;re looking for doesn&apos;t exist or you don&apos;t have access to it.
            </p>
            <Link
              href="/dashboard"
              className="mt-2 rounded-md bg-blue-500 px-4 py-2 text-sm font-medium text-white hover:bg-blue-600"
            >
              Back to Dashboard
            </Link>
          </div>
        </div>
      </header>

      <div className="flex-1">
        <FlowchartEditor
          projectId={project.id}
          initialData={flowchartData}
          needsMigration={needsMigration}
        />
      </div>
    </>
    )
  }

  const flowchartData = (project.flowchart_data || {
    nodes: [],
    edges: [],
  }) as FlowchartData

  return (
    <FlowchartEditor
      projectId={project.id}
      projectName={project.name}
      initialData={flowchartData}
    />
  )
}
