"use client";

import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { updateProduct, deleteProduct, reorderProduct, uploadImage } from "@/lib/content-actions";
import { Trash2, ChevronDown, ChevronUp, Upload } from "lucide-react";

export interface ProductRow {
  slug: string;
  name: string;
  short_name: string | null;
  tagline: string | null;
  description: string | null;
  icon: string | null;
  image_url: string | null;
  features: string[] | null;
  is_real_photo: boolean | null;
  name_en: string | null;
  tagline_en: string | null;
  description_en: string | null;
  features_en: string[] | null;
}

export default function ProductEditForm({
  product,
  isFirst,
  isLast,
}: {
  product: ProductRow;
  isFirst?: boolean;
  isLast?: boolean;
}) {
  const router = useRouter();
  const [isPending, startTransition] = useTransition();
  const [saved, setSaved] = useState(false);
  const [removed, setRemoved] = useState(false);
  const [open, setOpen] = useState(false);
  const [showEn, setShowEn] = useState(false);
  const [imageUrl, setImageUrl] = useState(product.image_url || "");
  const [isRealPhoto, setIsRealPhoto] = useState(!!product.is_real_photo);

  function handleSubmit(formData: FormData) {
    setSaved(false);
    startTransition(async () => {
      const result = await updateProduct(product.slug, formData);
      if (result.ok) setSaved(true);
    });
  }

  function handleDelete() {
    if (!confirm("حذف هذا المنتج نهائياً؟ سيختفي فوراً من الموقع.")) return;
    startTransition(async () => {
      const result = await deleteProduct(product.slug);
      if (result.ok) setRemoved(true);
    });
  }

  function handleReorder(dir: "up" | "down") {
    startTransition(async () => {
      const result = await reorderProduct(product.slug, dir);
      if (result.ok) router.refresh();
    });
  }

  function handleUpload(file: File | null) {
    if (!file) return;
    const formData = new FormData();
    formData.set("file", file);
    startTransition(async () => {
      const result = await uploadImage(formData);
      if (result.ok && result.url) setImageUrl(result.url);
    });
  }

  if (removed) return null;

  return (
    <form action={handleSubmit} className="rounded-2xl border border-black/10 bg-white p-6">
      <div className="flex items-center justify-between gap-3">
        <button
          type="button"
          onClick={() => setOpen((v) => !v)}
          className="flex min-w-0 flex-1 items-center gap-3 text-start"
        >
          <div className="flex h-12 w-12 shrink-0 items-center justify-center overflow-hidden rounded-lg border border-black/10 bg-[#F5F3EF]">
            {imageUrl ? (
              // eslint-disable-next-line @next/next/no-img-element
              <img src={imageUrl} alt="" className="h-full w-full object-cover" />
            ) : (
              <span className="text-[10px] text-[#B0B0B0]">بدون</span>
            )}
          </div>
          <div className="min-w-0">
            <h3 className="truncate font-bold text-[#1A1A1A]">{product.name}</h3>
            <p className="truncate font-mono text-[11px] text-[#B0B0B0]">{product.slug}</p>
          </div>
          {open ? (
            <ChevronUp size={16} className="shrink-0 text-[#B0B0B0]" />
          ) : (
            <ChevronDown size={16} className="shrink-0 text-[#B0B0B0]" />
          )}
        </button>

        <div className="flex shrink-0 items-center gap-1">
          <button
            type="button"
            onClick={() => handleReorder("up")}
            disabled={isFirst}
            className="rounded-lg p-1.5 text-[#B0B0B0] transition hover:bg-black/5 hover:text-[#1A1A1A] disabled:opacity-30"
            aria-label="تحريك لأعلى"
          >
            <ChevronUp size={15} />
          </button>
          <button
            type="button"
            onClick={() => handleReorder("down")}
            disabled={isLast}
            className="rounded-lg p-1.5 text-[#B0B0B0] transition hover:bg-black/5 hover:text-[#1A1A1A] disabled:opacity-30"
            aria-label="تحريك لأسفل"
          >
            <ChevronDown size={15} />
          </button>
          <button
            type="button"
            onClick={handleDelete}
            className="rounded-lg p-1.5 text-[#B0B0B0] transition hover:bg-red-50 hover:text-red-600"
            aria-label="حذف"
          >
            <Trash2 size={15} />
          </button>
        </div>
      </div>

      {!open && (
        <p className="mt-2 truncate text-xs text-[#8A8A8A]">
          {product.tagline || "اضغط للفتح والتعديل"}
        </p>
      )}

      {open && (
        <div className="mt-5 space-y-4">
          <div className="grid gap-4 sm:grid-cols-2">
            <Field name="name" label="الاسم" defaultValue={product.name} />
            <Field name="short_name" label="الاسم المختصر" defaultValue={product.short_name || ""} />
            <Field name="icon" label="اسم الأيقونة (lucide-react)" defaultValue={product.icon || ""} />
            <Field name="tagline" label="الوصف المختصر" defaultValue={product.tagline || ""} />
          </div>

          <div className="grid gap-4 sm:grid-cols-[auto_1fr]">
            <div className="flex w-full shrink-0 flex-col items-center gap-2 sm:w-40">
              <div className="flex h-24 w-full items-center justify-center overflow-hidden rounded-lg border border-black/10 bg-[#F5F3EF]">
                {imageUrl ? (
                  // eslint-disable-next-line @next/next/no-img-element
                  <img src={imageUrl} alt="" className="h-full w-full object-cover" />
                ) : (
                  <span className="text-[10px] text-[#B0B0B0]">لا توجد صورة</span>
                )}
              </div>
              <label className="flex w-full cursor-pointer items-center justify-center gap-1.5 rounded-lg bg-[#1A1A1A] px-3 py-1.5 text-[11px] font-semibold text-white transition hover:bg-black">
                <Upload size={12} />
                {isPending ? "جارِ الرفع..." : "رفع صورة"}
                <input
                  type="file"
                  accept="image/*"
                  className="hidden"
                  disabled={isPending}
                  onChange={(e) => handleUpload(e.target.files?.[0] || null)}
                />
              </label>
            </div>
            <div>
              <label className="mb-1.5 block text-sm font-semibold text-[#1A1A1A]">رابط الصورة</label>
              <input
                name="image_url"
                value={imageUrl}
                onChange={(e) => setImageUrl(e.target.value)}
                dir="ltr"
                className="w-full rounded-lg border border-black/10 bg-[#F5F3EF] px-4 py-2.5 text-sm outline-none focus:border-[#C9A24A]"
              />
              <label className="mt-3 flex w-fit cursor-pointer items-center gap-2 text-sm font-medium text-[#1A1A1A]">
                <input
                  type="checkbox"
                  name="is_real_photo"
                  checked={isRealPhoto}
                  onChange={(e) => setIsRealPhoto(e.target.checked)}
                  className="h-4 w-4 accent-[#C9A24A]"
                />
                صورة حقيقية من موقع العمل (تظهر في معرض الإنجازات)
              </label>
            </div>
          </div>

          <div>
            <label className="mb-1.5 block text-sm font-semibold text-[#1A1A1A]">الوصف الكامل</label>
            <textarea
              name="description"
              rows={3}
              defaultValue={product.description || ""}
              className="w-full resize-none rounded-lg border border-black/10 bg-[#F5F3EF] px-4 py-2.5 text-sm outline-none focus:border-[#C9A24A]"
            />
          </div>

          <div>
            <label className="mb-1.5 block text-sm font-semibold text-[#1A1A1A]">
              المميزات (كل ميزة في سطر)
            </label>
            <textarea
              name="features"
              rows={4}
              defaultValue={(product.features || []).join("\n")}
              className="w-full resize-none rounded-lg border border-black/10 bg-[#F5F3EF] px-4 py-2.5 text-sm outline-none focus:border-[#C9A24A]"
            />
          </div>

          <button
            type="button"
            onClick={() => setShowEn((v) => !v)}
            className="text-xs font-semibold text-[#8a6d1f] underline-offset-2 hover:underline"
          >
            {showEn ? "إخفاء النسخة الإنجليزية" : "تعديل النسخة الإنجليزية (اختياري)"}
          </button>

          {showEn && (
            <div className="space-y-3 rounded-lg border border-dashed border-black/10 p-4" dir="ltr">
              <Field name="name_en" label="Name (EN)" defaultValue={product.name_en || ""} />
              <Field name="tagline_en" label="Tagline (EN)" defaultValue={product.tagline_en || ""} />
              <div>
                <label className="mb-1.5 block text-sm font-semibold text-[#1A1A1A]">Description (EN)</label>
                <textarea
                  name="description_en"
                  rows={3}
                  defaultValue={product.description_en || ""}
                  className="w-full resize-none rounded-lg border border-black/10 bg-[#F5F3EF] px-4 py-2.5 text-sm outline-none focus:border-[#C9A24A]"
                />
              </div>
              <div>
                <label className="mb-1.5 block text-sm font-semibold text-[#1A1A1A]">Features (EN, one per line)</label>
                <textarea
                  name="features_en"
                  rows={3}
                  defaultValue={(product.features_en || []).join("\n")}
                  className="w-full resize-none rounded-lg border border-black/10 bg-[#F5F3EF] px-4 py-2.5 text-sm outline-none focus:border-[#C9A24A]"
                />
              </div>
            </div>
          )}

          <div className="flex items-center gap-3">
            <button
              type="submit"
              disabled={isPending}
              className="rounded-lg bg-[#1A1A1A] px-4 py-2 text-sm font-semibold text-white transition hover:bg-black disabled:opacity-60"
            >
              {isPending ? "جارِ الحفظ..." : "حفظ التغييرات"}
            </button>
            {saved && <span className="text-xs text-emerald-600">تم الحفظ ✓</span>}
          </div>
        </div>
      )}
    </form>
  );
}

function Field({
  name,
  label,
  defaultValue,
  className,
}: {
  name: string;
  label: string;
  defaultValue: string;
  className?: string;
}) {
  return (
    <div className={className}>
      <label className="mb-1.5 block text-sm font-semibold text-[#1A1A1A]">{label}</label>
      <input
        name={name}
        defaultValue={defaultValue}
        className="w-full rounded-lg border border-black/10 bg-[#F5F3EF] px-4 py-2.5 text-sm outline-none focus:border-[#C9A24A]"
      />
    </div>
  );
}