"use client";

import { useState, useEffect, useCallback } from "react";
import Link from "next/link";
import { ArrowLeft, Save, Eye, EyeOff, Loader2, ChevronDown, MonitorPlay } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Switch } from "@/components/ui/switch";
import { Separator } from "@/components/ui/separator";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import { ImageDropZone } from "@/components/admin/ImageDropZone";
import { useImageUpload } from "@/hooks/use-image-upload";
import { RichEditor } from "./RichEditor";
import { SeoPanel } from "./SeoPanel";
import { NewsPreview } from "./NewsPreview";
import { uploadToCloudinary } from "@/lib/cloudinary";
import type { NewsArticle, NewsFormData } from "@/lib/news";
import { NEWS_UPLOAD_SIGNATURE_ENDPOINT } from "@/lib/news";
import type { NewsCategory } from "@/services/news-categories";
import { useImageUpload as useOgImageUpload } from "@/hooks/use-image-upload";
import { getNewsCategories } from "@/services/news-categories";
import { toast } from "sonner";

function slugify(s: string): string {
  return s
    .toLowerCase()
    .replace(/[^a-z0-9\s-]/g, "")
    .trim()
    .replace(/[\s]+/g, "-")
    .replace(/--+/g, "-")
    .replace(/(^-|-$)/g, "");
}

// Extended form includes SEO fields + slug (omitted from base NewsFormData)
interface ExtendedForm extends NewsFormData {
  // NewsFormData already includes slug, seo_title, seo_description, focus_keyword, canonical_url, og_image
}

interface NewsEditorProps {
  initial?: NewsArticle;
  onSave: (data: NewsFormData) => Promise<void>;
}

export function NewsEditor({ initial, onSave }: NewsEditorProps) {
  const [saving, setSaving] = useState(false);
  const [previewOpen, setPreviewOpen] = useState(false);
  const [categories, setCategories] = useState<NewsCategory[]>([]);
  const [categoriesLoading, setCategoriesLoading] = useState(true);
  const [slugManuallyEdited, setSlugManuallyEdited] = useState(!!initial);
  const [seoOpen, setSeoOpen] = useState(false);

  const imgUpload = useImageUpload();
  const ogImgUpload = useOgImageUpload();
  const [coverUploading, setCoverUploading] = useState(false);
  const [ogUploading, setOgUploading] = useState(false);

  const [form, setForm] = useState<ExtendedForm>({
    title: initial?.title ?? "",
    slug: initial?.slug ?? "",
    excerpt: initial?.excerpt ?? "",
    content: initial?.content ?? "",
    image_url: initial?.image_url ?? null,
    image_public_id: initial?.image_public_id ?? null,
    og_image: initial?.og_image ?? null,
    og_image_public_id: initial?.og_image_public_id ?? null,
    category_id: initial?.category_id ?? null,
    author: initial?.author ?? "Petro-Base Group",
    published_at: initial?.published_at ?? new Date().toISOString().split("T")[0],
    is_published: initial?.is_published ?? false,
    seo_title: initial?.seo_title ?? "",
    seo_description: initial?.seo_description ?? "",
    focus_keyword: initial?.focus_keyword ?? "",
    canonical_url: initial?.canonical_url ?? "",
  });

  // Auto-generate slug from title until user manually edits it
  useEffect(() => {
    if (!slugManuallyEdited && form.title) {
      setForm((p) => ({ ...p, slug: slugify(p.title) }));
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [form.title]);

  // Load categories
  useEffect(() => {
    setCategoriesLoading(true);
    getNewsCategories()
      .then(setCategories)
      .catch(() => {})
      .finally(() => setCategoriesLoading(false));
  }, []);

  const set = useCallback(
    <K extends keyof ExtendedForm>(key: K) =>
      (val: ExtendedForm[K]) =>
        setForm((p) => ({ ...p, [key]: val })),
    [],
  );

  const handleCoverUpload = async () => {
    if (!imgUpload.file) return;
    setCoverUploading(true);
    try {
      const res = await uploadToCloudinary(imgUpload.file, "image", undefined, NEWS_UPLOAD_SIGNATURE_ENDPOINT);
      setForm((p) => ({ ...p, image_url: res.secure_url, image_public_id: res.public_id }));
      imgUpload.reset();
      toast.success("Cover image uploaded.");
    } catch {
      toast.error("Cover image upload failed.");
    } finally {
      setCoverUploading(false);
    }
  };

  const handleOgImageUpload = async () => {
    if (!ogImgUpload.file) return;
    setOgUploading(true);
    try {
      const res = await uploadToCloudinary(ogImgUpload.file, "image", undefined, NEWS_UPLOAD_SIGNATURE_ENDPOINT);
      setForm((p) => ({ ...p, og_image: res.secure_url, og_image_public_id: res.public_id }));
      ogImgUpload.reset();
      toast.success("OG image uploaded.");
    } catch {
      toast.error("OG image upload failed.");
    } finally {
      setOgUploading(false);
    }
  };

  const handleSave = async (publishOverride?: boolean) => {
    if (!form.title.trim()) { toast.error("Title is required."); return; }
    if (!form.excerpt.trim()) { toast.error("Excerpt is required."); return; }
    setSaving(true);
    try {
      const payload: NewsFormData = {
        ...form,
        is_published: publishOverride ?? form.is_published,
      };
      await onSave(payload);
    } finally {
      setSaving(false);
    }
  };

  const isPublishedState = form.is_published;

  return (
    <div className="flex flex-col min-h-screen bg-background">
      {/* ── Sticky top bar ── */}
      <div className="sticky top-0 z-20 bg-background/95 backdrop-blur-sm border-b border-border px-6 py-3 flex items-center gap-3">
        <Link href="/admin/news">
          <Button type="button" variant="ghost" size="sm" className="gap-1.5 text-muted-foreground hover:text-foreground h-8">
            <ArrowLeft size={14} />
            Back
          </Button>
        </Link>
        <Separator orientation="vertical" className="h-4" />
        <span className="text-sm text-muted-foreground font-medium">
          {initial ? "Edit Article" : "New Article"}
        </span>
        {form.slug && (
          <span className="text-xs text-muted-foreground/60 hidden sm:block truncate max-w-xs">
            /news/{form.slug}
          </span>
        )}
        <div className="ml-auto flex items-center gap-2">
          <Button
            type="button"
            variant="ghost"
            size="sm"
            onClick={() => setPreviewOpen(true)}
            className="gap-1.5 h-8 text-muted-foreground hover:text-foreground"
          >
            <MonitorPlay size={13} />
            Preview
          </Button>
          <Button
            type="button"
            variant="outline"
            size="sm"
            disabled={saving}
            onClick={() => handleSave(false)}
            className="gap-1.5 h-8"
          >
            {saving ? <Loader2 size={13} className="animate-spin" /> : <Save size={13} />}
            Save Draft
          </Button>
          <Button
            type="button"
            size="sm"
            disabled={saving}
            onClick={() => handleSave(true)}
            className="gap-1.5 h-8"
          >
            {isPublishedState ? <Eye size={13} /> : <EyeOff size={13} />}
            {initial?.is_published ? "Update" : "Publish"}
          </Button>
        </div>
      </div>

      {/* ── Main layout ── */}
      <div className="flex flex-1 gap-6 p-6 lg:p-8 max-w-screen-2xl mx-auto w-full">

        {/* Left: editor */}
        <div className="flex-1 min-w-0 space-y-4">
          <input
            value={form.title}
            onChange={(e) => set("title")(e.target.value)}
            placeholder="Article title…"
            className="w-full text-2xl lg:text-3xl font-bold bg-transparent border-none outline-none focus:ring-0 placeholder:text-muted-foreground/30 py-2"
          />
          <RichEditor
            value={form.content}
            onChange={set("content")}
            placeholder="Start writing your article…"
          />
        </div>

        {/* Right: sidebar */}
        <div className="w-72 shrink-0 space-y-4">

          {/* ── Publish card ── */}
          <Card>
            <CardHeader className="pb-3 pt-4">
              <CardTitle className="text-sm">Publish</CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              <div className="flex items-center justify-between">
                <Label htmlFor="is_published" className="text-sm cursor-pointer">
                  {isPublishedState ? "Published" : "Draft"}
                </Label>
                <Switch
                  id="is_published"
                  checked={isPublishedState}
                  onCheckedChange={set("is_published")}
                />
              </div>
              <div className="space-y-1.5">
                <Label className="text-xs text-muted-foreground">Publish Date</Label>
                <Input
                  type="date"
                  value={form.published_at}
                  onChange={(e) => set("published_at")(e.target.value)}
                  className="h-8 text-sm"
                />
              </div>
              <div className="space-y-1.5">
                <Label className="text-xs text-muted-foreground">Author</Label>
                <Input
                  value={form.author}
                  onChange={(e) => set("author")(e.target.value)}
                  className="h-8 text-sm"
                />
              </div>
              <div className="space-y-1.5">
                <Label className="text-xs text-muted-foreground">
                  Excerpt <span className="text-destructive">*</span>
                </Label>
                <Textarea
                  value={form.excerpt}
                  onChange={(e) => set("excerpt")(e.target.value)}
                  placeholder="Short summary shown on the listing page…"
                  rows={3}
                  className="text-sm resize-none"
                />
              </div>
            </CardContent>
          </Card>

          {/* ── Cover Image card ── */}
          <Card>
            <CardHeader className="pb-3 pt-4">
              <CardTitle className="text-sm">Cover Image</CardTitle>
            </CardHeader>
            <CardContent className="space-y-2">
              <input
                ref={imgUpload.inputRef}
                type="file"
                accept="image/*"
                className="hidden"
                onChange={(e) => {
                  const f = e.target.files?.[0];
                  if (f) imgUpload.handleFile(f);
                }}
              />
              <ImageDropZone
                preview={imgUpload.preview}
                fallback={form.image_url || undefined}
                isDragging={imgUpload.isDragging}
                onDragOver={(e) => { e.preventDefault(); imgUpload.setIsDragging(true); }}
                onDragLeave={() => imgUpload.setIsDragging(false)}
                onDrop={imgUpload.onDrop}
                onClick={() => imgUpload.inputRef.current?.click()}
              />
              {imgUpload.file && (
                <Button
                  type="button"
                  size="sm"
                  className="w-full h-7 text-xs"
                  disabled={coverUploading}
                  onClick={handleCoverUpload}
                >
                  {coverUploading
                    ? <><Loader2 size={11} className="animate-spin mr-1.5" />Uploading…</>
                    : "Upload to Cloudinary"}
                </Button>
              )}
              {form.image_url && !imgUpload.file && (
                <p className="text-[10px] text-muted-foreground truncate">{form.image_url}</p>
              )}
            </CardContent>
          </Card>

          {/* ── OG Image card ── */}
          <Card>
            <CardHeader className="pb-3 pt-4">
              <CardTitle className="text-sm">OG Image</CardTitle>
            </CardHeader>
            <CardContent className="space-y-2">
              <input
                ref={ogImgUpload.inputRef}
                type="file"
                accept="image/*"
                className="hidden"
                onChange={(e) => {
                  const f = e.target.files?.[0];
                  if (f) ogImgUpload.handleFile(f);
                }}
              />
              <ImageDropZone
                preview={ogImgUpload.preview}
                fallback={form.og_image || undefined}
                isDragging={ogImgUpload.isDragging}
                onDragOver={(e) => { e.preventDefault(); ogImgUpload.setIsDragging(true); }}
                onDragLeave={() => ogImgUpload.setIsDragging(false)}
                onDrop={ogImgUpload.onDrop}
                onClick={() => ogImgUpload.inputRef.current?.click()}
              />
              {ogImgUpload.file && (
                <Button
                  type="button"
                  size="sm"
                  className="w-full h-7 text-xs"
                  disabled={ogUploading}
                  onClick={handleOgImageUpload}
                >
                  {ogUploading
                    ? <><Loader2 size={11} className="animate-spin mr-1.5" />Uploading…</>
                    : "Upload to Cloudinary"}
                </Button>
              )}
              {form.og_image && !ogImgUpload.file && (
                <p className="text-[10px] text-muted-foreground truncate">{form.og_image}</p>
              )}
            </CardContent>
          </Card>

          {/* ── Category card ── */}
          <Card>
            <CardHeader className="pb-3 pt-4">
              <CardTitle className="text-sm">Category</CardTitle>
            </CardHeader>
            <CardContent>
              <Select
                value={form.category_id != null ? String(form.category_id) : ""}
                onValueChange={(v) => setForm((p) => ({ ...p, category_id: Number(v) }))}
                disabled={categoriesLoading}
              >
                <SelectTrigger className="h-8 text-sm">
                  <SelectValue placeholder={categoriesLoading ? "Loading…" : "Select category…"}>
                    {form.category_id != null
                      ? (categories.find((c) => c.id === form.category_id)?.name ?? "")
                      : null}
                  </SelectValue>
                </SelectTrigger>
                <SelectContent alignItemWithTrigger={false}>
                  {categories.map((c) => (
                    <SelectItem key={c.id} value={String(c.id)} className="text-sm">
                      {c.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </CardContent>
          </Card>

          {/* ── SEO card (collapsible) ── */}
          <Card>
            <Collapsible open={seoOpen} onOpenChange={setSeoOpen}>
              <CollapsibleTrigger className="w-full text-left">
                <CardHeader className="pb-3 pt-4 cursor-pointer select-none hover:bg-muted/30 rounded-t-lg transition-colors">
                  <div className="flex items-center justify-between">
                    <CardTitle className="text-sm">SEO Settings</CardTitle>
                    <ChevronDown
                      size={14}
                      className={`text-muted-foreground transition-transform duration-200 ${seoOpen ? "rotate-180" : ""}`}
                    />
                  </div>
                </CardHeader>
              </CollapsibleTrigger>
              <CollapsibleContent>
                <CardContent className="pt-0">
                  <SeoPanel
                    focusKeyword={form.focus_keyword}
                    seoTitle={form.seo_title}
                    seoDescription={form.seo_description}
                    slug={form.slug}
                    contentHtml={form.content}
                    excerpt={form.excerpt}
                    coverImage={form.image_url ?? ""}
                    title={form.title}
                    onFocusKeyword={set("focus_keyword")}
                    onSeoTitle={set("seo_title")}
                    onSeoDescription={set("seo_description")}
                    onSlug={(v) => {
                      setSlugManuallyEdited(true);
                      set("slug")(v);
                    }}
                  />
                </CardContent>
              </CollapsibleContent>
            </Collapsible>
          </Card>

        </div>
      </div>
      <NewsPreview
        open={previewOpen}
        onClose={() => setPreviewOpen(false)}
        title={form.title}
        excerpt={form.excerpt}
        content={form.content}
        image={form.image_url ?? ""}
        category={categories.find((c) => c.id === form.category_id)?.name ?? ""}
        author={form.author}
        published_at={form.published_at}
      />
    </div>
  );
}
