"use client";

import { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import { AppForm } from "@/components/app-form";

export default function EditAppPage() {
  const params = useParams<{ slug: string }>();
  const [data, setData] = useState<{
    name: string;
    slug: string;
    description: string;
    appUrl: string;
    primaryColor: string;
    accentColor: string;
    darkBg: string;
    brandIdentity: string;
    productInfo: string;
    platformGuidelines: string;
  } | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  useEffect(() => {
    fetch(`/api/apps/${params.slug}`)
      .then((r) => {
        if (!r.ok) throw new Error("Not found");
        return r.json();
      })
      .then((app) => {
        setData({
          name: app.name,
          slug: app.slug,
          description: app.description || "",
          appUrl: app.appUrl || "",
          primaryColor: app.primaryColor,
          accentColor: app.accentColor,
          darkBg: app.darkBg,
          brandIdentity: app.brandIdentity || "",
          productInfo: app.productInfo || "",
          platformGuidelines: app.platformGuidelines || "",
        });
        setLoading(false);
      })
      .catch(() => {
        setError("App not found");
        setLoading(false);
      });
  }, [params.slug]);

  if (loading) return <div className="text-muted-foreground">Loading...</div>;
  if (error) return <div className="text-red-500">{error}</div>;
  if (!data) return null;

  return (
    <div className="mx-auto max-w-2xl">
      <AppForm mode="edit" initialData={data} />
    </div>
  );
}
