"use client";

import { useEffect, useMemo, useState } from "react";
import Image from "next/image";
import Link from "next/link";
import { useParams } from "next/navigation";
import { toast } from "react-toastify";
import {
  ArrowLeft,
  BookOpen,
  Eye,
  FileImage,
  FileVideo,
  Globe2,
  ImageUp,
  Loader2,
  Save,
  Search,
  Tags,
  Trash2,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { BlogCategorySelection } from "@/components/blogs/blog-category-selection";
import { AdminBreadcrumb } from "@/components/admin/admin-breadcrumb";
import { DatePickerInput } from "@/components/ui/date-picker-input";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { RichTextEditor } from "@/components/ui/rich-text-editor";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Textarea } from "@/components/ui/textarea";
import {
  apiRequest,
  apiUrl,
  mediaUrl,
  shouldBypassImageOptimization,
} from "@/lib/api";
import { getLocalizedApiMessage } from "@/lib/api-message";
import { useAuth } from "@/lib/auth-context";

type ApiBlogCategory = {
  id?: string | number;
  uuid?: string;
  category_uuid?: string;
  title?: string;
  name?: string;
};

type BlogMedia = {
  uuid?: string;
  file_path?: string;
  file_type?: string;
  mime_type?: string;
  type?: string;
  title?: string;
};

type GuideBlog = {
  id?: string | number;
  uuid?: string;
  title?: string;
  title_hi?: string | null;
  slug?: string | null;
  content?: string | null;
  content_hi?: string | null;
  meta_title?: string | null;
  meta_description?: string | null;
  meta_keywords?: string | null;
  og_title?: string | null;
  og_description?: string | null;
  published_at?: string | null;
  banner_image?: string | null;
  media?: BlogMedia[];
  categories?: ApiBlogCategory[];
};

type GuideBlogDetailApiResponse = {
  success?: boolean;
  data?: GuideBlog | GuideBlogDetailData;
  message?: string;
  message_hi?: string;
};

type GuideBlogDetailData = {
  blog?: GuideBlog;
  blogs?: GuideBlog;
  data?: GuideBlog;
};

type BlogCategoriesApiResponse = {
  success?: boolean;
  data?:
    | ApiBlogCategory[]
    | {
        categories?: ApiBlogCategory[];
        blog_categories?: ApiBlogCategory[];
        data?: ApiBlogCategory[];
      };
  message?: string;
  message_hi?: string;
};

type BlogForm = {
  title: string;
  title_hi: string;
  content: string;
  content_hi: string;
  banner_image: string;
  published_at: string;
  meta_title: string;
  meta_description: string;
  meta_keywords: string;
  og_title: string;
  og_description: string;
  category_uuids: string[];
};

type SaveAction = "general" | "categories" | "media" | "";
type BlogEditTab = "general" | "categories" | "gallery";

const initialForm: BlogForm = {
  title: "",
  title_hi: "",
  content: "",
  content_hi: "",
  banner_image: "",
  published_at: "",
  meta_title: "",
  meta_description: "",
  meta_keywords: "",
  og_title: "",
  og_description: "",
  category_uuids: [],
};

const allowedImageTypes = ["image/jpeg", "image/png", "image/webp"];
const allowedMediaTypes = [
  "image/jpeg",
  "image/png",
  "image/webp",
  "application/pdf",
  "video/mp4",
  "video/quicktime",
  "video/x-msvideo",
];
const MAX_IMAGE_SIZE = 5 * 1024 * 1024;
const MAX_MEDIA_SIZE = 20 * 1024 * 1024;

function isUuid(value?: string | null) {
  return Boolean(
    value &&
    /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(
      value,
    ),
  );
}

function getBlogFromDetailResponse(result: GuideBlogDetailApiResponse) {
  if (!result.data) return null;

  if ("title" in result.data || "uuid" in result.data || "id" in result.data) {
    return result.data as GuideBlog;
  }

  const detailData = result.data as GuideBlogDetailData;
  return detailData.blog || detailData.blogs || detailData.data || null;
}

function getCategoryList(result: BlogCategoriesApiResponse) {
  if (Array.isArray(result.data)) return result.data;
  return (
    result.data?.categories ||
    result.data?.blog_categories ||
    result.data?.data ||
    []
  );
}

function getCategoryUuid(category: ApiBlogCategory) {
  const idValue = String(category.id || "");
  const uuid = String(
    category.uuid || category.category_uuid || (isUuid(idValue) ? idValue : ""),
  );

  return isUuid(uuid) ? uuid : "";
}

function getCategoryLabel(category: ApiBlogCategory) {
  return (
    category.title ||
    category.name ||
    String(category.uuid || category.id || "")
  );
}

function getPlainTextFromHtml(value: string) {
  return value
    .replace(/<[^>]*>/g, " ")
    .replace(/&nbsp;/g, " ")
    .replace(/\s+/g, " ")
    .trim();
}

function calculateReadTimeMinutes(value: string) {
  const text = getPlainTextFromHtml(value);

  if (!text) {
    return 0;
  }

  return Math.max(1, Math.ceil(text.split(/\s+/).filter(Boolean).length / 200));
}

function validateImageFile(file: File, label: string) {
  if (!allowedImageTypes.includes(file.type)) {
    return `${label} must be jpg, jpeg, png, or webp.`;
  }

  if (file.size > MAX_IMAGE_SIZE) {
    return `${label} must not be greater than 5 MB.`;
  }

  return "";
}

function validateMediaFile(file: File) {
  if (!allowedMediaTypes.includes(file.type)) {
    return "Media must be jpg, jpeg, png, webp, pdf, mp4, mov, or avi.";
  }

  if (file.size > MAX_MEDIA_SIZE) {
    return "Media file must not be greater than 20 MB.";
  }

  return "";
}

function validateVideoFile(file: File) {
  if (
    !["video/mp4", "video/quicktime", "video/x-msvideo"].includes(file.type)
  ) {
    return "Video must be mp4, mov, or avi.";
  }

  if (file.size > MAX_MEDIA_SIZE) {
    return "Video file must not be greater than 20 MB.";
  }

  return "";
}

function isImageFile(file: File) {
  return allowedImageTypes.includes(file.type);
}

function isVideoFile(file: File) {
  return ["video/mp4", "video/quicktime", "video/x-msvideo"].includes(
    file.type,
  );
}

function blogToForm(blog: GuideBlog): BlogForm {
  return {
    title: blog.title || "",
    title_hi: blog.title_hi || "",
    content: blog.content || "",
    content_hi: blog.content_hi || "",
    banner_image: blog.banner_image || "",
    published_at: blog.published_at?.split("T")[0] || "",
    meta_title: blog.meta_title || blog.title || "",
    meta_description: blog.meta_description || "",
    meta_keywords: blog.meta_keywords || "",
    og_title: blog.og_title || blog.title || "",
    og_description: blog.og_description || blog.meta_description || "",
    category_uuids: (blog.categories || [])
      .map(getCategoryUuid)
      .filter(Boolean),
  };
}

function isImageMedia(media: BlogMedia) {
  const type = media.mime_type || media.file_type || media.type || "";
  const path = media.file_path || "";

  return type.startsWith("image/") || /\.(jpe?g|png|webp|gif)$/i.test(path);
}

function isVideoMedia(media: BlogMedia) {
  const type = media.mime_type || media.file_type || media.type || "";
  const path = media.file_path || "";

  return type.startsWith("video/") || /\.(mp4|mov|avi)$/i.test(path);
}

function NewMediaPreviewCard({
  file,
  index,
  onRemove,
}: {
  file: File;
  index: number;
  onRemove: (index: number) => void;
}) {
  const [previewUrl, setPreviewUrl] = useState("");

  useEffect(() => {
    const nextPreviewUrl = URL.createObjectURL(file);
    setPreviewUrl(nextPreviewUrl);

    return () => URL.revokeObjectURL(nextPreviewUrl);
  }, [file]);

  return (
    <div className="overflow-hidden rounded-2xl border border-[var(--theme-border-soft)] bg-white shadow-sm">
      <div className="relative aspect-video bg-[var(--theme-surface)]">
        {!previewUrl ? (
          <div className="flex h-full w-full items-center justify-center text-xs font-semibold text-muted-foreground">
            Preparing preview...
          </div>
        ) : isImageFile(file) ? (
          <img
            src={previewUrl}
            alt={file.name}
            className="h-full w-full object-cover"
          />
        ) : (
          <video
            src={previewUrl}
            className="h-full w-full object-cover"
            controls
          />
        )}
      </div>
      <div className="flex items-center justify-between gap-3 px-3 py-3">
        <p className="min-w-0 truncate text-sm font-bold text-foreground">
          {file.name}
        </p>
        <Button
          type="button"
          size="sm"
          variant="ghost"
          className="h-8 shrink-0 rounded-lg px-2.5 text-xs text-red-600 hover:bg-red-50 hover:text-red-700"
          onClick={() => onRemove(index)}
        >
          <Trash2 className="mr-1 h-3.5 w-3.5" />
          Remove
        </Button>
      </div>
    </div>
  );
}

function FieldLabel({
  htmlFor,
  children,
}: {
  htmlFor?: string;
  children: React.ReactNode;
}) {
  return (
    <Label htmlFor={htmlFor} className="text-sm font-bold">
      {children}
    </Label>
  );
}

function ExistingMediaCard({
  item,
  index,
  isRemoved,
  replacement,
  onReplace,
  onRemove,
}: {
  item: BlogMedia;
  index: number;
  isRemoved: boolean;
  replacement?: File;
  onReplace: (uuid: string, file: File | null) => void;
  onRemove: (uuid: string) => void;
}) {
  const [replacementPreviewUrl, setReplacementPreviewUrl] = useState("");
  const src = mediaUrl(item.file_path);
  const uuid = item.uuid || "";
  const inputId = `existing-media-${uuid || index}`;
  const itemIsImage = isImageMedia(item);
  const showImage = replacement ? isImageFile(replacement) : itemIsImage;
  const visibleSrc = replacementPreviewUrl || src;

  useEffect(() => {
    if (!replacement) {
      setReplacementPreviewUrl("");
      return;
    }

    const nextPreviewUrl = URL.createObjectURL(replacement);
    setReplacementPreviewUrl(nextPreviewUrl);

    return () => URL.revokeObjectURL(nextPreviewUrl);
  }, [replacement]);

  return (
    <div
      className={`overflow-hidden rounded-2xl border border-[var(--theme-border-soft)] bg-white shadow-sm ${
        isRemoved ? "opacity-50" : ""
      }`}
    >
      <div className="relative aspect-video bg-[var(--theme-surface)]">
        {showImage ? (
          <Image
            src={visibleSrc || "/placeholder.jpg"}
            alt={item.title || replacement?.name || "Blog media"}
            fill
            unoptimized={shouldBypassImageOptimization(visibleSrc)}
            className="object-cover"
          />
        ) : visibleSrc ? (
          <video
            src={visibleSrc}
            className="h-full w-full object-cover"
            controls
          />
        ) : (
          <div className="flex h-full w-full items-center justify-center text-xs font-semibold text-muted-foreground">
            Media preview unavailable
          </div>
        )}
        <div className="absolute inset-0 bg-gradient-to-t from-black/65 via-black/10 to-transparent" />
        <Input
          id={inputId}
          type="file"
          disabled={isRemoved}
          accept={
            itemIsImage
              ? "image/jpeg,image/png,image/webp"
              : "video/mp4,video/quicktime,video/x-msvideo"
          }
          onChange={(event) => {
            onReplace(uuid, event.target.files?.[0] || null);
            event.target.value = "";
          }}
          className="sr-only"
        />
        {uuid && (
          <div className="absolute inset-x-2 bottom-2 z-10 flex flex-wrap justify-center gap-1.5">
            {src && (
              <Link
                href={src}
                target="_blank"
                rel="noopener noreferrer"
                className="inline-flex h-8 items-center justify-center rounded-full bg-white px-3 text-xs font-black text-[var(--theme-primary)] shadow-md transition hover:bg-[var(--theme-surface-strong)]"
              >
                <Eye className="mr-1.5 h-3.5 w-3.5" />
                Preview
              </Link>
            )}
            <Label
              htmlFor={inputId}
              className="inline-flex h-8 cursor-pointer items-center justify-center rounded-full bg-white px-3 text-xs font-black text-[var(--theme-primary)] shadow-md transition hover:bg-[var(--theme-surface-strong)]"
            >
              {itemIsImage ? "Image" : "Video"}
            </Label>
            <Button
              type="button"
              size="sm"
              variant="outline"
              className="h-8 rounded-full border-white/35 bg-black/35 px-3 text-xs font-black text-white shadow-md backdrop-blur hover:bg-black/50 hover:text-white"
              onClick={() => onRemove(uuid)}
            >
              <Trash2 className="mr-1.5 h-3.5 w-3.5" />
              {isRemoved ? "Undo" : "Remove"}
            </Button>
          </div>
        )}
      </div>
      <div className="truncate px-3 py-2 text-xs font-semibold text-muted-foreground">
        {replacement?.name || item.title || item.file_path || "Media file"}
      </div>
    </div>
  );
}

function MediaGrid({
  items,
  emptyText,
  removedUuids,
  updateFiles,
  onReplace,
  onRemove,
}: {
  items: BlogMedia[];
  emptyText: string;
  removedUuids: string[];
  updateFiles: Record<string, File>;
  onReplace: (uuid: string, file: File | null) => void;
  onRemove: (uuid: string) => void;
}) {
  if (!items.length) {
    return (
      <div className="rounded-2xl border border-dashed border-[var(--theme-border-soft)] bg-[var(--theme-surface)] px-4 py-8 text-center text-sm font-semibold text-muted-foreground">
        {emptyText}
      </div>
    );
  }

  return (
    <div className="grid gap-4 md:grid-cols-3">
      {items.map((item, index) => {
        const uuid = item.uuid || "";
        const isRemoved = uuid ? removedUuids.includes(uuid) : false;
        const replacement = uuid ? updateFiles[uuid] : undefined;

        return (
          <ExistingMediaCard
            key={item.uuid || item.file_path || index}
            item={item}
            index={index}
            isRemoved={isRemoved}
            replacement={replacement}
            onReplace={onReplace}
            onRemove={onRemove}
          />
        );
      })}
    </div>
  );
}

export default function EditBlogPage() {
  const params = useParams<{ id: string }>();
  const blogId = decodeURIComponent(params.id || "");
  const { token, isLoading: isAuthLoading } = useAuth();
  const [form, setForm] = useState<BlogForm>(initialForm);
  const [blog, setBlog] = useState<GuideBlog | null>(null);
  const [categories, setCategories] = useState<ApiBlogCategory[]>([]);
  const [bannerFile, setBannerFile] = useState<File | null>(null);
  const [bannerPreviewUrl, setBannerPreviewUrl] = useState("");
  const [newMediaFiles, setNewMediaFiles] = useState<File[]>([]);
  const [updateMediaFiles, setUpdateMediaFiles] = useState<
    Record<string, File>
  >({});
  const [removeMediaUuids, setRemoveMediaUuids] = useState<string[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [savingAction, setSavingAction] = useState<SaveAction>("");
  const [error, setError] = useState("");
  const [reloadKey, setReloadKey] = useState(0);
  const [activeTab, setActiveTab] = useState<BlogEditTab>("general");

  useEffect(() => {
    if (!bannerFile) {
      setBannerPreviewUrl("");
      return;
    }

    const nextPreviewUrl = URL.createObjectURL(bannerFile);
    setBannerPreviewUrl(nextPreviewUrl);

    return () => URL.revokeObjectURL(nextPreviewUrl);
  }, [bannerFile]);

  useEffect(() => {
    if (isAuthLoading) return;

    let isMounted = true;

    async function loadData() {
      setIsLoading(true);
      setError("");

      try {
        const activeToken =
          token ||
          (typeof window !== "undefined"
            ? localStorage.getItem("auth_token")
            : null);

        if (!activeToken) {
          throw new Error("Authentication token missing. Please login again.");
        }

        if (!blogId) {
          throw new Error("Blog UUID missing. Please go back and try again.");
        }

        const [blogResponse, categoriesResponse] = await Promise.all([
          apiRequest(apiUrl(`/admin/blogs/${encodeURIComponent(blogId)}`), {
            headers: {
              Authorization: `Bearer ${activeToken}`,
              Accept: "application/json",
            },
          }),
          apiRequest(apiUrl("/blog-categories"), {
            headers: {
              Authorization: `Bearer ${activeToken}`,
              Accept: "application/json",
            },
          }),
        ]);

        const blogResult =
          (await blogResponse.json()) as GuideBlogDetailApiResponse;
        const categoriesResult =
          (await categoriesResponse.json()) as BlogCategoriesApiResponse;

        if (!blogResponse.ok || blogResult.success === false) {
          throw new Error(
            getLocalizedApiMessage(blogResult, "Failed to load blog."),
          );
        }

        const selectedBlog = getBlogFromDetailResponse(blogResult);

        if (!selectedBlog) {
          throw new Error("Blog post not found.");
        }

        if (isMounted) {
          setBlog(selectedBlog);
          setForm(blogToForm(selectedBlog));
          setBannerFile(null);
          setNewMediaFiles([]);
          setUpdateMediaFiles({});
          setRemoveMediaUuids([]);
          setCategories(
            categoriesResponse.ok && categoriesResult.success !== false
              ? getCategoryList(categoriesResult).filter((category) =>
                  Boolean(getCategoryUuid(category)),
                )
              : [],
          );
        }
      } catch (loadError) {
        if (isMounted) {
          setError(
            loadError instanceof Error
              ? loadError.message
              : "Failed to load blog.",
          );
        }
      } finally {
        if (isMounted) {
          setIsLoading(false);
        }
      }
    }

    loadData();

    return () => {
      isMounted = false;
    };
  }, [blogId, isAuthLoading, reloadKey, token]);

  const photos = useMemo(
    () => (blog?.media || []).filter(isImageMedia),
    [blog?.media],
  );
  const videos = useMemo(
    () => (blog?.media || []).filter(isVideoMedia),
    [blog?.media],
  );
  const newImageFiles = useMemo(
    () =>
      newMediaFiles
        .map((file, index) => ({ file, index }))
        .filter(({ file }) => isImageFile(file)),
    [newMediaFiles],
  );
  const newVideoFiles = useMemo(
    () =>
      newMediaFiles
        .map((file, index) => ({ file, index }))
        .filter(({ file }) => isVideoFile(file)),
    [newMediaFiles],
  );
  const bannerSrc = mediaUrl(form.banner_image) || "/placeholder.jpg";
  const visibleBannerSrc = bannerPreviewUrl || bannerSrc;
  const existingBannerSrc = mediaUrl(form.banner_image);

  const setField = <K extends keyof BlogForm>(field: K, value: BlogForm[K]) => {
    setForm((current) => ({ ...current, [field]: value }));
  };

  const getActiveToken = () =>
    token ||
    (typeof window !== "undefined" ? localStorage.getItem("auth_token") : null);

  const getBlogUuid = () => {
    const uuid = blog?.uuid || (isUuid(blogId) ? blogId : "");

    if (!uuid) {
      toast.error("Blog UUID not found.");
    }

    return uuid;
  };

  const toggleCategory = (uuid: string) => {
    setForm((current) => ({
      ...current,
      category_uuids: current.category_uuids.includes(uuid)
        ? current.category_uuids.filter((item) => item !== uuid)
        : [...current.category_uuids, uuid],
    }));
  };

  const appendNewMedia = (files: FileList | null, type: "image" | "video") => {
    if (!files?.length) return;

    const nextFiles = Array.from(files);
    const getError =
      type === "image"
        ? (file: File) => validateImageFile(file, "Image")
        : validateVideoFile;
    const invalidFile = nextFiles.find((file) => getError(file));

    if (invalidFile) {
      toast.error(getError(invalidFile));
      return;
    }

    setNewMediaFiles((current) => [...current, ...nextFiles]);
  };

  const removeNewMedia = (index: number) => {
    setNewMediaFiles((current) =>
      current.filter((_, itemIndex) => itemIndex !== index),
    );
  };

  const replaceExistingMedia = (uuid: string, file: File | null) => {
    if (!file) return;

    const error = validateMediaFile(file);

    if (error) {
      toast.error(error);
      return;
    }

    setUpdateMediaFiles((current) => ({ ...current, [uuid]: file }));
  };

  const toggleRemoveExistingMedia = (uuid: string) => {
    setRemoveMediaUuids((current) =>
      current.includes(uuid)
        ? current.filter((item) => item !== uuid)
        : [...current, uuid],
    );
    setUpdateMediaFiles((current) => {
      const next = { ...current };
      delete next[uuid];
      return next;
    });
  };

  const saveGeneral = async () => {
    const activeToken = getActiveToken();
    const blogUuid = getBlogUuid();

    if (!activeToken || !blogUuid) {
      toast.error("Authentication token missing. Please login again.");
      return;
    }

    setSavingAction("general");

    try {
      const payload = new FormData();
      payload.append("title", form.title.trim());
      payload.append("title_hi", form.title_hi.trim());
      payload.append("content", form.content.trim());
      payload.append("content_hi", form.content_hi.trim());
      payload.append(
        "read_time",
        String(calculateReadTimeMinutes(form.content)),
      );
      payload.append("published_at", form.published_at);
      payload.append("meta_title", form.meta_title.trim());
      payload.append("meta_description", form.meta_description.trim());
      payload.append("meta_keywords", form.meta_keywords.trim());
      payload.append("og_title", form.og_title.trim());
      payload.append("og_description", form.og_description.trim());

      if (bannerFile) {
        payload.append("banner_image", bannerFile);
      }

      const response = await apiRequest(
        apiUrl(`/admin/blogs/${encodeURIComponent(blogUuid)}/data`),
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${activeToken}`,
            Accept: "application/json",
          },
          body: payload,
        },
      );
      const result = await response.json();

      if (!response.ok || result?.success === false) {
        toast.error(getLocalizedApiMessage(result, "Blog update failed."));
        return;
      }

      toast.success(getLocalizedApiMessage(result, "Blog updated."));
      setReloadKey((current) => current + 1);
    } catch {
      toast.error("Unable to connect to the blog server.");
    } finally {
      setSavingAction("");
    }
  };

  const saveCategories = async () => {
    const activeToken = getActiveToken();
    const blogUuid = getBlogUuid();

    if (!activeToken || !blogUuid) {
      toast.error("Authentication token missing. Please login again.");
      return;
    }

    setSavingAction("categories");

    try {
      const response = await apiRequest(
        apiUrl(`/admin/blogs/${encodeURIComponent(blogUuid)}/categories`),
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${activeToken}`,
            Accept: "application/json",
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            category_uuids: form.category_uuids.filter(isUuid),
          }),
        },
      );
      const result = await response.json();

      if (!response.ok || result?.success === false) {
        toast.error(getLocalizedApiMessage(result, "Category update failed."));
        return;
      }

      toast.success(getLocalizedApiMessage(result, "Categories updated."));
      setActiveTab("categories");
      setReloadKey((current) => current + 1);
    } catch {
      toast.error("Unable to connect to the blog server.");
    } finally {
      setSavingAction("");
    }
  };

  const saveMedia = async () => {
    const activeToken = getActiveToken();
    const blogUuid = getBlogUuid();

    if (!activeToken || !blogUuid) {
      toast.error("Authentication token missing. Please login again.");
      return;
    }

    setSavingAction("media");

    try {
      const payload = new FormData();
      newMediaFiles.forEach((file) => payload.append("new_media[]", file));
      Object.entries(updateMediaFiles).forEach(([uuid, file], index) => {
        payload.append(`update_media[${index}][uuid]`, uuid);
        payload.append(`update_media[${index}][file]`, file);
      });
      removeMediaUuids.forEach((uuid) =>
        payload.append("remove_media_uuids[]", uuid),
      );

      const response = await apiRequest(
        apiUrl(`/admin/blogs/${encodeURIComponent(blogUuid)}/media`),
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${activeToken}`,
            Accept: "application/json",
          },
          body: payload,
        },
      );
      const result = await response.json();

      if (!response.ok || result?.success === false) {
        toast.error(getLocalizedApiMessage(result, "Media update failed."));
        return;
      }

      toast.success(getLocalizedApiMessage(result, "Media updated."));
      setReloadKey((current) => current + 1);
    } catch {
      toast.error("Unable to connect to the blog server.");
    } finally {
      setSavingAction("");
    }
  };

  if (isLoading) {
    return (
      <div className="space-y-5">
        <AdminBreadcrumb
          current="Edit Blog"
          parent="My Blogs"
          parentHref="/admin/blogs"
        />
        <Card className="rounded-3xl border-[var(--theme-border)] bg-white py-0 shadow-sm">
          <CardContent className="flex min-h-64 items-center justify-center py-16">
            <Loader2 className="h-10 w-10 animate-spin text-[var(--theme-primary)]" />
          </CardContent>
        </Card>
      </div>
    );
  }

  if (error) {
    return (
      <div className="space-y-5">
        <AdminBreadcrumb
          current="Edit Blog"
          parent="My Blogs"
          parentHref="/admin/blogs"
        />
        <Card className="rounded-3xl border-red-200 bg-red-50 py-0 shadow-sm">
          <CardContent className="p-5">
            <p className="font-bold text-red-900">{error}</p>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="space-y-5">
      <AdminBreadcrumb
        current="Edit Blog"
        parent="My Blogs"
        parentHref="/admin/blogs"
      />

      <div className="flex flex-col gap-3 rounded-3xl border border-[var(--theme-border)] bg-white p-5 shadow-sm sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-black text-foreground">Edit Blog</h1>
          <p className="mt-1 text-sm font-medium text-muted-foreground">
            Manage blog content, categories, and gallery.
          </p>
        </div>
        <Link href="/admin/blogs">
          <Button variant="outline" className="rounded-xl">
            <ArrowLeft className="mr-2 h-4 w-4" />
            Back to Blogs
          </Button>
        </Link>
      </div>

      <Tabs
        value={activeTab}
        onValueChange={(value) => setActiveTab(value as BlogEditTab)}
        className="gap-5"
      >
        <TabsList className="h-auto w-fit max-w-full justify-start overflow-x-auto rounded-full border border-[var(--theme-border)] bg-white p-1 shadow-sm">
          <TabsTrigger
            value="general"
            className="rounded-full px-5 py-2 data-[state=active]:bg-[var(--theme-primary)] data-[state=active]:text-white"
          >
            General
          </TabsTrigger>
          <TabsTrigger
            value="categories"
            className="rounded-full px-5 py-2 data-[state=active]:bg-[var(--theme-primary)] data-[state=active]:text-white"
          >
            Category Management
          </TabsTrigger>
          <TabsTrigger
            value="gallery"
            className="rounded-full px-5 py-2 data-[state=active]:bg-[var(--theme-primary)] data-[state=active]:text-white"
          >
            Blog Gallery
          </TabsTrigger>
        </TabsList>

        <TabsContent value="general" className="space-y-5">
          <Card className="overflow-hidden rounded-3xl border-[var(--theme-border)] bg-white py-0 shadow-sm">
            <div className="relative flex aspect-[21/8] min-h-56 items-center justify-center overflow-hidden bg-[var(--theme-surface)]">
              <Image
                src={visibleBannerSrc}
                alt="Blog banner"
                fill
                unoptimized={shouldBypassImageOptimization(visibleBannerSrc)}
                className="object-cover"
              />
              <div className="absolute inset-0 bg-black/25" />
              <div className="relative z-10 text-center text-white">
                <ImageUp className="mx-auto mb-2 h-8 w-8" />
                <p className="text-sm font-semibold">
                  {bannerFile ? bannerFile.name : "Banner Image"}
                </p>
              </div>
              <Input
                id="banner-image"
                type="file"
                accept="image/jpeg,image/png,image/webp"
                onChange={(event) => {
                  const file = event.target.files?.[0] || null;
                  const error = file
                    ? validateImageFile(file, "Banner image")
                    : "";

                  if (error) {
                    toast.error(error);
                    event.target.value = "";
                    return;
                  }

                  setBannerFile(file);
                }}
                className="sr-only"
              />
              <div className="absolute bottom-5 right-5 z-20 flex flex-wrap justify-end gap-3">
                {existingBannerSrc && (
                  <Link
                    href={existingBannerSrc}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="inline-flex h-11 items-center justify-center rounded-full bg-white/90 px-5 text-sm font-black text-[var(--theme-primary)] shadow-lg backdrop-blur transition hover:bg-white"
                  >
                    <Eye className="mr-2 h-4 w-4" />
                    Preview Existing
                  </Link>
                )}
                <Label
                  htmlFor="banner-image"
                  className="inline-flex h-11 cursor-pointer items-center justify-center rounded-full bg-white px-5 text-sm font-black text-[var(--theme-primary)] shadow-lg transition hover:bg-[var(--theme-surface-strong)]"
                >
                  Choose Image
                </Label>
                <Button
                  type="button"
                  variant="outline"
                  className="h-11 rounded-full border-white/40 bg-black/35 px-5 font-black text-white shadow-lg backdrop-blur hover:bg-black/50 hover:text-white"
                  onClick={() => setBannerFile(null)}
                  disabled={!bannerFile}
                >
                  <Trash2 className="mr-2 h-4 w-4" />
                  Remove
                </Button>
              </div>
            </div>
          </Card>

          <Card className="rounded-3xl border-[var(--theme-border)] bg-white py-0 shadow-sm">
            <CardHeader className="px-5 pt-5">
              <CardTitle className="flex items-center gap-2 text-xl font-black">
                <BookOpen className="h-5 w-5 text-[var(--theme-primary)]" />
                Blog Content
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-5 p-5 pt-2">
              <div className="grid gap-4 md:grid-cols-2">
                <div className="space-y-2">
                  <FieldLabel htmlFor="blog-title">Title</FieldLabel>
                  <Input
                    id="blog-title"
                    value={form.title}
                    onChange={(event) => setField("title", event.target.value)}
                    className="h-11 rounded-xl border-[var(--theme-border-soft)] bg-[var(--theme-surface)]"
                  />
                </div>
                <div className="space-y-2">
                  <FieldLabel htmlFor="blog-title-hi">Title Hindi</FieldLabel>
                  <Input
                    id="blog-title-hi"
                    value={form.title_hi}
                    onChange={(event) =>
                      setField("title_hi", event.target.value)
                    }
                    className="h-11 rounded-xl border-[var(--theme-border-soft)] bg-[var(--theme-surface)]"
                  />
                </div>
                <div className="space-y-2">
                  <FieldLabel htmlFor="published-at">Published At</FieldLabel>
                  <DatePickerInput
                    id="published-at"
                    value={form.published_at}
                    onValueChange={(value) => setField("published_at", value)}
                    className="h-11 border-[var(--theme-border-soft)] bg-[var(--theme-surface)]"
                  />
                </div>
              </div>
              <div className="space-y-2">
                <FieldLabel htmlFor="blog-content">Content</FieldLabel>
                <RichTextEditor
                  id="blog-content"
                  value={form.content}
                  onChange={(value) => setField("content", value)}
                />
              </div>
              <div className="space-y-2">
                <FieldLabel htmlFor="blog-content-hi">Content Hindi</FieldLabel>
                <RichTextEditor
                  id="blog-content-hi"
                  value={form.content_hi}
                  onChange={(value) => setField("content_hi", value)}
                  minHeightClassName="min-h-[220px]"
                />
              </div>
            </CardContent>
          </Card>

          <Card className="rounded-3xl border-[var(--theme-border)] bg-white py-0 shadow-sm">
            <CardHeader className="px-5 pt-5">
              <CardTitle className="flex items-center gap-2 text-xl font-black">
                <Search className="h-5 w-5 text-[var(--theme-primary)]" />
                SEO Meta
              </CardTitle>
            </CardHeader>
            <CardContent className="grid gap-4 p-5 pt-2 md:grid-cols-2">
              <div className="space-y-2">
                <FieldLabel htmlFor="meta-title">Meta Title</FieldLabel>
                <Input
                  id="meta-title"
                  value={form.meta_title}
                  onChange={(event) =>
                    setField("meta_title", event.target.value)
                  }
                  className="h-11 rounded-xl border-[var(--theme-border-soft)] bg-[var(--theme-surface)]"
                />
              </div>
              <div className="space-y-2">
                <FieldLabel htmlFor="meta-keywords">Meta Keywords</FieldLabel>
                <Input
                  id="meta-keywords"
                  value={form.meta_keywords}
                  onChange={(event) =>
                    setField("meta_keywords", event.target.value)
                  }
                  className="h-11 rounded-xl border-[var(--theme-border-soft)] bg-[var(--theme-surface)]"
                />
              </div>
              <div className="space-y-2 md:col-span-2">
                <FieldLabel htmlFor="meta-description">
                  Meta Description
                </FieldLabel>
                <Textarea
                  id="meta-description"
                  value={form.meta_description}
                  onChange={(event) =>
                    setField("meta_description", event.target.value)
                  }
                  rows={3}
                  className="rounded-xl border-[var(--theme-border-soft)] bg-[var(--theme-surface)]"
                />
              </div>
            </CardContent>
          </Card>

          <Card className="rounded-3xl border-[var(--theme-border)] bg-white py-0 shadow-sm">
            <CardHeader className="px-5 pt-5">
              <CardTitle className="flex items-center gap-2 text-xl font-black">
                <Globe2 className="h-5 w-5 text-[var(--theme-primary)]" />
                Open Graph
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4 p-5 pt-2">
              <div className="space-y-2">
                <FieldLabel htmlFor="og-title">OG Title</FieldLabel>
                <Input
                  id="og-title"
                  value={form.og_title}
                  onChange={(event) => setField("og_title", event.target.value)}
                  className="h-11 rounded-xl border-[var(--theme-border-soft)] bg-[var(--theme-surface)]"
                />
              </div>
              <div className="space-y-2">
                <FieldLabel htmlFor="og-description">OG Description</FieldLabel>
                <Textarea
                  id="og-description"
                  value={form.og_description}
                  onChange={(event) =>
                    setField("og_description", event.target.value)
                  }
                  rows={3}
                  className="rounded-xl border-[var(--theme-border-soft)] bg-[var(--theme-surface)]"
                />
              </div>
            </CardContent>
          </Card>

          <div className="flex justify-end">
            <Button
              type="button"
              onClick={saveGeneral}
              disabled={savingAction === "general"}
              className="rounded-xl bg-[var(--theme-primary)] hover:bg-[var(--theme-accent-dark)]"
            >
              {savingAction === "general" ? (
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              ) : (
                <Save className="mr-2 h-4 w-4" />
              )}
              Save General
            </Button>
          </div>
        </TabsContent>

        <TabsContent value="categories">
          <Card className="rounded-3xl border-[var(--theme-border)] bg-white py-0 shadow-sm">
            <CardHeader className="px-5 pt-5">
              <CardTitle className="flex items-center gap-2 text-xl font-black">
                <Tags className="h-5 w-5 text-[var(--theme-primary)]" />
                Category Management
              </CardTitle>
              <CardDescription>
                Select one or more blog categories.
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4 p-5 pt-2">
              <BlogCategorySelection
                categories={categories.map((category) => ({
                  uuid: getCategoryUuid(category),
                  title: getCategoryLabel(category),
                }))}
                selectedUuids={form.category_uuids}
                onToggle={toggleCategory}
              />
              <div className="flex justify-end">
                <Button
                  type="button"
                  onClick={saveCategories}
                  disabled={savingAction === "categories"}
                  className="rounded-xl bg-[var(--theme-primary)] hover:bg-[var(--theme-accent-dark)]"
                >
                  {savingAction === "categories" ? (
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  ) : (
                    <Save className="mr-2 h-4 w-4" />
                  )}
                  Save Categories
                </Button>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="gallery" className="space-y-5">
          <Card className="rounded-3xl border-[var(--theme-border)] bg-white py-0 shadow-sm">
            <CardHeader className="px-5 pt-5">
              <CardTitle className="text-xl font-black">Add Media</CardTitle>
              <CardDescription>
                Upload new photos and videos to this blog.
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4 p-5 pt-2">
              <div className="grid gap-4 lg:grid-cols-2">
                <div className="rounded-2xl border border-[var(--theme-border-soft)] bg-[var(--theme-surface)] p-4">
                  <div className="mb-3 flex items-center gap-2">
                    <FileImage className="h-5 w-5 text-[var(--theme-primary)]" />
                    <div>
                      <h3 className="font-black text-foreground">
                        Upload Images
                      </h3>
                      <p className="text-xs font-medium text-muted-foreground">
                        JPG, PNG, or WEBP up to 5 MB each.
                      </p>
                    </div>
                  </div>
                  <Input
                    type="file"
                    multiple
                    accept="image/jpeg,image/png,image/webp"
                    onChange={(event) => {
                      appendNewMedia(event.target.files, "image");
                      event.target.value = "";
                    }}
                    className="h-11 rounded-xl border-[var(--theme-border-soft)] bg-white"
                  />
                </div>

                <div className="rounded-2xl border border-[var(--theme-border-soft)] bg-[var(--theme-surface)] p-4">
                  <div className="mb-3 flex items-center gap-2">
                    <FileVideo className="h-5 w-5 text-[var(--theme-primary)]" />
                    <div>
                      <h3 className="font-black text-foreground">
                        Upload Videos
                      </h3>
                      <p className="text-xs font-medium text-muted-foreground">
                        MP4, MOV, or AVI up to 20 MB each.
                      </p>
                    </div>
                  </div>
                  <Input
                    type="file"
                    multiple
                    accept="video/mp4,video/quicktime,video/x-msvideo"
                    onChange={(event) => {
                      appendNewMedia(event.target.files, "video");
                      event.target.value = "";
                    }}
                    className="h-11 rounded-xl border-[var(--theme-border-soft)] bg-white"
                  />
                </div>
              </div>

              {newImageFiles.length > 0 && (
                <div className="space-y-3">
                  <h3 className="text-sm font-black text-foreground">
                    New Image Previews
                  </h3>
                  <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
                    {newImageFiles.map(({ file, index }) => (
                      <NewMediaPreviewCard
                        key={`${file.name}-${file.lastModified}-${index}`}
                        file={file}
                        index={index}
                        onRemove={removeNewMedia}
                      />
                    ))}
                  </div>
                </div>
              )}

              {newVideoFiles.length > 0 && (
                <div className="space-y-3">
                  <h3 className="text-sm font-black text-foreground">
                    New Video Previews
                  </h3>
                  <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
                    {newVideoFiles.map(({ file, index }) => (
                      <NewMediaPreviewCard
                        key={`${file.name}-${file.lastModified}-${index}`}
                        file={file}
                        index={index}
                        onRemove={removeNewMedia}
                      />
                    ))}
                  </div>
                </div>
              )}
            </CardContent>
          </Card>

          <Card className="rounded-3xl border-[var(--theme-border)] bg-white py-0 shadow-sm">
            <CardHeader className="px-5 pt-5">
              <CardTitle className="flex items-center gap-2 text-xl font-black">
                <FileImage className="h-5 w-5 text-[var(--theme-primary)]" />
                Photos
              </CardTitle>
            </CardHeader>
            <CardContent className="p-5 pt-2">
              <MediaGrid
                items={photos}
                emptyText="No photos uploaded."
                removedUuids={removeMediaUuids}
                updateFiles={updateMediaFiles}
                onReplace={replaceExistingMedia}
                onRemove={toggleRemoveExistingMedia}
              />
            </CardContent>
          </Card>

          <Card className="rounded-3xl border-[var(--theme-border)] bg-white py-0 shadow-sm">
            <CardHeader className="px-5 pt-5">
              <CardTitle className="flex items-center gap-2 text-xl font-black">
                <FileVideo className="h-5 w-5 text-[var(--theme-primary)]" />
                Videos
              </CardTitle>
            </CardHeader>
            <CardContent className="p-5 pt-2">
              <MediaGrid
                items={videos}
                emptyText="No videos uploaded."
                removedUuids={removeMediaUuids}
                updateFiles={updateMediaFiles}
                onReplace={replaceExistingMedia}
                onRemove={toggleRemoveExistingMedia}
              />
            </CardContent>
          </Card>
          <div className="flex justify-end">
            <Button
              type="button"
              onClick={saveMedia}
              disabled={savingAction === "media"}
              className="rounded-xl bg-[var(--theme-primary)] hover:bg-[var(--theme-accent-dark)]"
            >
              {savingAction === "media" ? (
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              ) : (
                <Save className="mr-2 h-4 w-4" />
              )}
              Save Gallery
            </Button>
          </div>
        </TabsContent>
      </Tabs>
    </div>
  );
}
