import { Suspense } from "react";
import { notFound } from "next/navigation";
import { Metadata } from "next";
import MainLayout from "@/components/layout/MainLayout";
import { CandidateForm } from "@/components/candidates/CandidateForm";
import { requireAuth } from "@/lib/auth";
import { connectToDatabase } from "@/lib/db";
import { Candidate } from "@/models/Candidate";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";

export const metadata: Metadata = {
  title: "Edit Candidate - Candidate Portal",
  description: "Edit candidate information",
};

interface EditCandidatePageProps {
  params: {
    id: string;
  };
}

async function getCandidateById(id: string) {
  await connectToDatabase();
  const candidate = await Candidate.findById(id);

  if (!candidate) {
    return null;
  }

  return JSON.parse(JSON.stringify(candidate));
}

function FormSkeleton() {
  return (
    <div className="space-y-6">
      <div className="space-y-2">
        <Skeleton className="h-6 w-1/3" />
        <Skeleton className="h-4 w-1/2" />
      </div>
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {Array.from({ length: 8 }).map((_, i) => (
          <div key={i} className="space-y-2">
            <Skeleton className="h-4 w-20" />
            <Skeleton className="h-10 w-full" />
          </div>
        ))}
      </div>
      <Skeleton className="h-32 w-full" />
      <div className="flex justify-end space-x-2">
        <Skeleton className="h-10 w-24" />
        <Skeleton className="h-10 w-32" />
      </div>
    </div>
  );
}

export default async function EditCandidatePage({
  params,
}: EditCandidatePageProps) {
  // Ensure user is authenticated
  await requireAuth();

  const candidateData = await getCandidateById(params.id);

  if (!candidateData) {
    notFound();
  }

  return (
    <MainLayout>
      <div className="flex flex-col space-y-6">
        <Card>
          <CardHeader>
            <CardTitle>Edit Candidate</CardTitle>
            <CardDescription>
              Update information for {candidateData.name}
            </CardDescription>
          </CardHeader>
          <CardContent>
            <Suspense fallback={<FormSkeleton />}>
              <CandidateForm
                initialData={candidateData}
                isEditing={true}
              />
            </Suspense>
          </CardContent>
        </Card>
      </div>
    </MainLayout>
  );
}
