"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import type { BlogCategory } from "@prisma/client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

type PostInitial = {
  titleFa: string;
  slug: string;
  excerptFa: string;
  content: string;
  coverImageUrl: string | null;
  youtubeUrls: string;
  status: string;
  publishedAt: string;
  categoryId: string;
};

export function BlogPostForm({
  categories,
  postId,
  initial,
}: {
  categories: BlogCategory[];
  postId?: string;
  initial?: PostInitial;
}) {
  const router = useRouter();
  const [titleFa, setTitleFa] = useState(initial?.titleFa ?? "");
  const [slug, setSlug] = useState(initial?.slug ?? "");
  const [excerptFa, setExcerptFa] = useState(initial?.excerptFa ?? "");
  const [content, setContent] = useState(initial?.content ?? "");
  const [coverImageUrl, setCoverImageUrl] = useState(initial?.coverImageUrl ?? "");
  const [youtubeUrls, setYoutubeUrls] = useState(initial?.youtubeUrls ?? "");
  const [status, setStatus] = useState(initial?.status ?? "DRAFT");
  const [publishedAt, setPublishedAt] = useState(initial?.publishedAt ?? "");
  const [categoryId, setCategoryId] = useState(initial?.categoryId ?? categories[0]?.id ?? "");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [coverUploading, setCoverUploading] = useState(false);
  const [coverFile, setCoverFile] = useState<File | null>(null);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    setLoading(true);
    const urls = youtubeUrls
      .split("\n")
      .map((s) => s.trim())
      .filter(Boolean);
    const body = {
      titleFa,
      slug: slug.trim(),
      excerptFa,
      content,
      coverImageUrl: coverImageUrl || undefined,
      youtubeUrls: urls,
      status,
      publishedAt: publishedAt ? new Date(publishedAt).toISOString() : undefined,
      categoryId: categoryId || categories[0]?.id || "",
    };
    const url = postId ? `/api/admin/blog/${postId}` : "/api/admin/blog";
    const res = await fetch(url, {
      method: postId ? "PATCH" : "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body),
    });
    const data = await res.json().catch(() => ({}));
    setLoading(false);
    if (res.ok) {
      router.push("/admin/blog");
    } else {
      setError((data.error as string) || "خطا در ذخیره");
      router.refresh();
    }
  }

  async function handleCoverFileChange(e: React.ChangeEvent<HTMLInputElement>) {
    const f = e.target.files?.[0];
    if (!f) return;
    if (!f.type.startsWith("image/")) {
      setError("لطفاً یک فایل تصویری (JPG، PNG، GIF یا WebP) انتخاب کنید.");
      return;
    }
    setError(null);
    setCoverFile(f);
    setCoverUploading(true);
    try {
      const form = new FormData();
      form.set("file", f);
      const res = await fetch("/api/admin/upload", { method: "POST", body: form });
      const data = await res.json().catch(() => ({}));
      if (res.ok && data.url) {
        setCoverImageUrl(data.url);
      } else {
        setError((data.error as string) || "خطا در آپلود تصویر");
      }
    } catch {
      setError("خطا در آپلود تصویر");
    } finally {
      setCoverUploading(false);
      setCoverFile(null);
      e.target.value = "";
    }
  }

  function clearCoverImage() {
    setCoverImageUrl("");
    setCoverFile(null);
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      {error && (
        <p className="text-sm text-destructive bg-destructive/10 p-3 rounded-md" role="alert">
          {error}
        </p>
      )}
      {categories.length === 0 && (
        <p className="text-sm text-amber-600 bg-amber-50 dark:bg-amber-950/30 p-3 rounded-md">
          ابتدا یک دسته‌بندی برای وبلاگ ایجاد کنید.
        </p>
      )}
      <div>
        <Label>عنوان (فارسی)</Label>
        <Input
          value={titleFa}
          onChange={(e) => {
            setTitleFa(e.target.value);
            if (!postId && !slug) setSlug(e.target.value.replace(/\s+/g, "-").toLowerCase());
          }}
          className="mt-1"
        />
      </div>
      <div>
        <Label>اسلاگ</Label>
        <Input value={slug} onChange={(e) => setSlug(e.target.value)} className="mt-1" />
      </div>
      <div>
        <Label>خلاصه</Label>
        <textarea
          value={excerptFa}
          onChange={(e) => setExcerptFa(e.target.value)}
          className="flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm mt-1"
        />
      </div>
      <div>
        <Label>محتوا</Label>
        <textarea
          value={content}
          onChange={(e) => setContent(e.target.value)}
          className="flex min-h-[200px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm mt-1"
        />
      </div>
      <div>
        <Label>تصویر کاور</Label>
        <p className="text-xs text-muted-foreground mt-1 mb-2">
          آدرس تصویر را وارد کنید یا فایل را از دستگاه انتخاب کنید.
        </p>
        <div className="flex flex-wrap gap-2 items-center mt-1">
          <Input
            value={coverImageUrl}
            onChange={(e) => {
              setCoverImageUrl(e.target.value);
              setCoverFile(null);
            }}
            placeholder="https://..."
            className="max-w-md"
          />
          <label className="cursor-pointer">
            <input
              type="file"
              accept="image/jpeg,image/png,image/webp"
              className="sr-only"
              disabled={coverUploading}
              onChange={handleCoverFileChange}
            />
            <span className="inline-flex items-center justify-center rounded-md text-sm font-medium bg-primary text-primary-foreground h-10 px-4 hover:bg-primary/90 disabled:opacity-50">
              {coverUploading ? "در حال آپلود..." : "انتخاب فایل"}
            </span>
          </label>
          {(coverImageUrl || coverFile) && (
            <Button type="button" variant="outline" size="sm" onClick={clearCoverImage}>
              پاک کردن
            </Button>
          )}
        </div>
        {coverImageUrl && (
          <div className="mt-2 relative inline-block">
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img
              src={coverImageUrl}
              alt="پیش‌نمایش کاور"
              className="max-h-32 rounded border object-cover"
            />
          </div>
        )}
      </div>
      <div>
        <Label>لینک‌های ویدیو — یوتیوب یا آپارات (هر خط یک لینک)</Label>
        <textarea
          value={youtubeUrls}
          onChange={(e) => setYoutubeUrls(e.target.value)}
          className="flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm mt-1"
          placeholder="https://youtube.com/... یا https://www.aparat.com/v/..."
        />
      </div>
      <div>
        <Label>دسته</Label>
        <select
          value={categoryId}
          onChange={(e) => setCategoryId(e.target.value)}
          className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm mt-1"
        >
          {categories.map((c) => (
            <option key={c.id} value={c.id}>
              {c.nameFa}
            </option>
          ))}
        </select>
      </div>
      <div>
        <Label>وضعیت</Label>
        <select
          value={status}
          onChange={(e) => setStatus(e.target.value)}
          className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm mt-1"
        >
          <option value="DRAFT">پیش‌نویس</option>
          <option value="PUBLISHED">منتشر شده</option>
        </select>
      </div>
      <div>
        <Label>تاریخ انتشار (اختیاری)</Label>
        <Input
          type="datetime-local"
          value={publishedAt}
          onChange={(e) => setPublishedAt(e.target.value)}
          className="mt-1"
        />
      </div>
      <Button type="submit" disabled={loading || categories.length === 0}>
        {loading ? "در حال ذخیره..." : postId ? "بروزرسانی" : "ایجاد"}
      </Button>
    </form>
  );
}
