"use client";

import { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import AdminForm from "@/components/admin/admin-form";
import FileUpload from "@/components/admin/file-upload";
import { createProject, updateProject } from "@/app/admin/(protected)/projects/actions";
import { projectSchema, type ProjectInput } from "@/lib/validations/project";
import { useRouter } from "next/navigation";

type CategoryOption = {
  id: string;
  nameAr: string;
  nameEn: string;
};

type ProjectFormProps = {
  mode: "create" | "edit";
  projectId?: string;
  categories: CategoryOption[];
  defaultValues: ProjectInput;
};

const typeLabels: Record<ProjectInput["type"], string> = {
  PORTFOLIO: "Portfolio",
  APP: "App",
  WEBSITE: "Website",
  DESIGN: "Design",
};

const statusLabels: Record<ProjectInput["status"], string> = {
  DRAFT: "Draft",
  PUBLISHED: "Published",
  ARCHIVED: "Archived",
};

function parseList(value: string) {
  return value
    .split(/\r?\n|,/)
    .map((item) => item.trim())
    .filter(Boolean);
}

export default function ProjectForm({ mode, projectId, categories, defaultValues }: ProjectFormProps) {
  const router = useRouter();
  const [serverError, setServerError] = useState<string | null>(null);
  const form = useForm<ProjectInput>({
    resolver: zodResolver(projectSchema),
    defaultValues,
  });
  const projectType = form.watch("type");

  const onSubmit = async (values: ProjectInput) => {
    setServerError(null);
    const result = mode === "create" ? await createProject(values) : await updateProject(projectId ?? "", values);

    if (result.error) {
      setServerError(result.error);
      return;
    }

    router.push("/admin/projects");
    router.refresh();
  };

  return (
    <AdminForm
      form={form}
      onSubmit={onSubmit}
      submitLabel={mode === "create" ? "Create project" : "Save changes"}
      submittingLabel="Saving…"
      className="max-w-3xl"
    >
      <div className="grid gap-5 md:grid-cols-2">
        <FormField
          control={form.control}
          name="type"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Project type</FormLabel>
              <Select value={field.value} onValueChange={field.onChange}>
                <FormControl>
                  <SelectTrigger>
                    <SelectValue placeholder="Choose a type" />
                  </SelectTrigger>
                </FormControl>
                <SelectContent>
                  {Object.entries(typeLabels).map(([value, label]) => (
                    <SelectItem key={value} value={value}>
                      {label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name="status"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Status</FormLabel>
              <Select value={field.value} onValueChange={field.onChange}>
                <FormControl>
                  <SelectTrigger>
                    <SelectValue placeholder="Choose a status" />
                  </SelectTrigger>
                </FormControl>
                <SelectContent>
                  {Object.entries(statusLabels).map(([value, label]) => (
                    <SelectItem key={value} value={value}>
                      {label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <FormMessage />
            </FormItem>
          )}
        />
      </div>

      <FormField
        control={form.control}
        name="slug"
        render={({ field }) => (
          <FormItem>
            <FormLabel>Slug</FormLabel>
            <FormControl>
              <Input placeholder="project-slug" {...field} />
            </FormControl>
            <FormMessage />
          </FormItem>
        )}
      />

      <div className="grid gap-5 md:grid-cols-2">
        <FormField
          control={form.control}
          name="titleEn"
          render={({ field }) => (
            <FormItem>
              <FormLabel>English title</FormLabel>
              <FormControl>
                <Input {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name="titleAr"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Arabic title</FormLabel>
              <FormControl>
                <Input dir="rtl" {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
      </div>

      <div className="grid gap-5 md:grid-cols-2">
        <FormField
          control={form.control}
          name="summaryEn"
          render={({ field }) => (
            <FormItem>
              <FormLabel>English summary</FormLabel>
              <FormControl>
                <Input {...field} value={field.value ?? ""} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name="summaryAr"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Arabic summary</FormLabel>
              <FormControl>
                <Input dir="rtl" {...field} value={field.value ?? ""} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
      </div>

      <div className="grid gap-5 md:grid-cols-2">
        <FormField
          control={form.control}
          name="descEn"
          render={({ field }) => (
            <FormItem>
              <FormLabel>English description</FormLabel>
              <FormControl>
                <textarea className="min-h-32 w-full rounded-md border border-input bg-background px-3 py-2 text-sm" {...field} value={field.value ?? ""} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name="descAr"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Arabic description</FormLabel>
              <FormControl>
                <textarea dir="rtl" className="min-h-32 w-full rounded-md border border-input bg-background px-3 py-2 text-sm" {...field} value={field.value ?? ""} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
      </div>

      <FormField
        control={form.control}
        name="categoryId"
        render={({ field }) => (
          <FormItem>
            <FormLabel>Project category</FormLabel>
            <Select value={field.value || "__none"} onValueChange={(value) => field.onChange(value === "__none" ? "" : value)}>
              <FormControl>
                <SelectTrigger>
                  <SelectValue placeholder="Choose a category" />
                </SelectTrigger>
              </FormControl>
              <SelectContent>
                <SelectItem value="__none">No category</SelectItem>
                {categories.map((category) => (
                  <SelectItem key={category.id} value={category.id}>
                    {category.nameEn} · {category.nameAr}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            <FormMessage />
          </FormItem>
        )}
      />

      <div className="grid gap-5 md:grid-cols-2">
        <FormField
          control={form.control}
          name="coverImage"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Cover image path</FormLabel>
              <FormControl>
                <Input placeholder="/api/uploads/images/..." {...field} value={field.value ?? ""} />
              </FormControl>
              <FormMessage />
              <FileUpload
                id="project-cover-image"
                kind="image"
                label="Upload cover image"
                onUploaded={(files) => field.onChange(files[0]?.url ?? field.value ?? "")}
              />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name="images"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Gallery image paths</FormLabel>
              <FormControl>
                <textarea
                  className="min-h-32 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                  placeholder="One uploaded path per line"
                  value={field.value.join("\n")}
                  onChange={(event) => field.onChange(parseList(event.target.value))}
                />
              </FormControl>
              <FormMessage />
              <FileUpload
                id="project-gallery-images"
                kind="image"
                label="Upload gallery images"
                multiple
                onUploaded={(files) => field.onChange([...field.value, ...files.map((file) => file.url)])}
              />
            </FormItem>
          )}
        />
      </div>

      <FormField
        control={form.control}
        name="technologies"
        render={({ field }) => (
          <FormItem>
            <FormLabel>Technologies</FormLabel>
            <FormControl>
              <textarea
                className="min-h-24 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                placeholder="Next.js, TypeScript, PostgreSQL"
                value={field.value.join("\n")}
                onChange={(event) => field.onChange(parseList(event.target.value))}
              />
            </FormControl>
            <FormMessage />
          </FormItem>
        )}
      />

      <div className="grid gap-5 md:grid-cols-2">
        <FormField
          control={form.control}
          name="externalUrl"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Live / external URL</FormLabel>
              <FormControl>
                <Input type="url" placeholder="https://example.com" {...field} value={field.value ?? ""} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name="repoUrl"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Repository URL</FormLabel>
              <FormControl>
                <Input type="url" placeholder="https://github.com/..." {...field} value={field.value ?? ""} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
      </div>

      <div className="grid gap-5 md:grid-cols-2">
        <FormField
          control={form.control}
          name="sortOrder"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Sort order</FormLabel>
              <FormControl>
                <Input type="number" min={0} max={9999} value={field.value} onChange={(event) => field.onChange(event.target.valueAsNumber || 0)} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name="isFeatured"
          render={({ field }) => (
            <FormItem className="flex items-center gap-3 rounded-md border border-border p-3 md:mt-7">
              <FormControl>
                <Input type="checkbox" checked={field.value} onChange={(event) => field.onChange(event.target.checked)} className="h-4 w-4" />
              </FormControl>
              <FormLabel className="m-0">Feature this project</FormLabel>
            </FormItem>
          )}
        />
      </div>

      {projectType === "APP" ? (
        <section className="space-y-5 rounded-xl border border-border bg-card p-5">
          <div>
            <h2 className="text-lg font-semibold">iOS app details</h2>
            <p className="mt-1 text-sm text-muted-foreground">Add the store, release, and support details for this application.</p>
          </div>

          <div className="grid gap-5 md:grid-cols-2">
            <FormField
              control={form.control}
              name="platform"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Platform</FormLabel>
                  <FormControl>
                    <Input placeholder="iOS / Swift" {...field} value={field.value ?? ""} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="appVersion"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>App version</FormLabel>
                  <FormControl>
                    <Input placeholder="1.0.0" {...field} value={field.value ?? ""} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          </div>

          <div className="grid gap-5 md:grid-cols-2">
            {([
              ["appStoreUrl", "App Store URL"],
              ["testflightUrl", "TestFlight URL"],
              ["supportUrl", "Support URL"],
              ["appPrivacyUrl", "App privacy URL"],
            ] as const).map(([name, label]) => (
              <FormField
                key={name}
                control={form.control}
                name={name}
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{label}</FormLabel>
                    <FormControl>
                      <Input type="url" placeholder="https://..." {...field} value={field.value ?? ""} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            ))}
          </div>
        </section>
      ) : null}

      {serverError ? <p className="text-sm font-medium text-destructive">{serverError}</p> : null}
    </AdminForm>
  );
}
