"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { toast } from "react-toastify";
import {
  ArrowLeft,
  BookOpen,
  CircleHelp,
  FileImage,
  FileVideo,
  Globe2,
  Info,
  Loader2,
  Save,
  Search,
  Send,
  Tags,
  Trash2,
} from "lucide-react";
import { Alert, AlertDescription } from "@/components/ui/alert";
import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from "@/components/ui/accordion";
import { Badge } from "@/components/ui/badge";
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,
  formatDateForApi,
} 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 { Textarea } from "@/components/ui/textarea";
import { apiRequest, apiUrl } from "@/lib/api";
import { getLocalizedApiMessage } from "@/lib/api-message";
import { useAuth } from "@/lib/auth-context";

type BlogStatus = "draft" | "submitted";

type BlogCategory = {
  uuid: string;
  title: string;
};

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

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

type BlogForm = {
  title: string;
  title_hi: string;
  content: string;
  content_hi: string;
  banner_image: File | null;
  status: BlogStatus;
  published_at: string;
  meta_title: string;
  meta_description: string;
  meta_keywords: string;
  og_title: string;
  og_description: string;
  category_uuids: string[];
  media_images: File[];
  media_videos: File[];
};

type BlogValidationData = BlogForm & {
  slug: string;
  read_time: number;
  media: File[];
};

type BlogValidationErrors = Record<string, string>;

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;

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

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

function getApiCategoryList(result: BlogCategoriesApiResponse) {
  if (Array.isArray(result.data)) {
    return result.data;
  }

  return (
    result.data?.categories ||
    result.data?.blog_categories ||
    result.data?.data ||
    []
  );
}

function isUuid(value: string) {
  return /^[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 mapBlogCategory(category: ApiBlogCategory): BlogCategory | null {
  const idValue = String(category.id || "");
  const uuid = String(
    category.uuid || category.category_uuid || (isUuid(idValue) ? idValue : ""),
  );
  const title = category.title || category.name || "";

  if (!uuid || !isUuid(uuid) || !title) {
    return null;
  }

  return { uuid, title };
}

function formatFileSize(size: number) {
  if (size < 1024 * 1024) {
    return `${Math.max(1, Math.round(size / 1024))} KB`;
  }

  return `${(size / (1024 * 1024)).toFixed(1)} MB`;
}

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

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

  if (!text) {
    return 0;
  }

  const wordCount = text.split(/\s+/).filter(Boolean).length;

  return Math.max(1, Math.ceil(wordCount / 200));
}

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

  if (text.length <= 160) {
    return text;
  }

  return `${text.slice(0, 157).trimEnd()}...`;
}

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 validateBlogForm(data: BlogValidationData) {
  const errors: BlogValidationErrors = {};

  if (!data.title || data.title.trim() === "") {
    errors.title = "Title is required.";
  } else if (data.title.length > 255) {
    errors.title = "Title must not be greater than 255 characters.";
  }

  if (data.title_hi && data.title_hi.length > 255) {
    errors.title_hi = "Hindi title must not be greater than 255 characters.";
  }

  if (data.slug && data.slug.length > 255) {
    errors.slug = "Slug must not be greater than 255 characters.";
  }

  if (data.read_time < 0) {
    errors.read_time = "Read time must be 0 or greater.";
  }

  if (!data.category_uuids.length) {
    errors.category_uuids = "At least one category is required.";
  } else if (data.category_uuids.some((uuid) => !isUuid(uuid))) {
    errors.category_uuids = "Selected category must be a valid UUID.";
  }

  if (data.meta_title && data.meta_title.length > 255) {
    errors.meta_title = "Meta title must not be greater than 255 characters.";
  }

  if (data.og_title && data.og_title.length > 255) {
    errors.og_title = "OG title must not be greater than 255 characters.";
  }

  if (data.banner_image) {
    const bannerError = validateImageFile(data.banner_image, "Banner image");

    if (bannerError) {
      errors.banner_image = bannerError;
    }
  }

  data.media.forEach((file, index) => {
    const mediaError = validateMediaFile(file);

    if (mediaError) {
      errors[`media.${index}`] = mediaError;
    }
  });

  return errors;
}

function getFirstValidationError(errors: BlogValidationErrors) {
  return Object.values(errors)[0] || "";
}

function getBlogRequestStatus(submitAction: BlogStatus) {
  return submitAction === "draft" ? "draft" : "submitted";
}

function FieldLabel({
  htmlFor,
  children,
  required = false,
}: {
  htmlFor?: string;
  children: React.ReactNode;
  required?: boolean;
}) {
  return (
    <Label htmlFor={htmlFor} className="text-sm font-bold">
      {children}
      {required && <span className="ml-1 text-[var(--theme-accent)]">*</span>}
    </Label>
  );
}

function FileList({
  files,
  onRemove,
}: {
  files: File[];
  onRemove: (index: number) => void;
}) {
  if (files.length === 0) {
    return null;
  }

  return (
    <div className="mt-3 grid gap-2">
      {files.map((file, index) => (
        <div
          key={`${file.name}-${file.lastModified}-${index}`}
          className="flex min-h-11 items-center justify-between gap-3 rounded-xl border border-[var(--theme-border-soft)] bg-[var(--theme-surface)] px-3 py-2 text-sm"
        >
          <div className="min-w-0">
            <p className="truncate font-bold text-foreground">{file.name}</p>
            <p className="text-xs font-medium text-muted-foreground">
              {formatFileSize(file.size)}
            </p>
          </div>
          <Button
            type="button"
            variant="ghost"
            size="icon"
            className="h-8 w-8 shrink-0 rounded-full text-red-600 hover:bg-red-50 hover:text-red-700"
            onClick={() => onRemove(index)}
            aria-label={`Remove ${file.name}`}
          >
            <Trash2 className="h-4 w-4" />
          </Button>
        </div>
      ))}
    </div>
  );
}

export default function NewBlogPage() {
  const router = useRouter();
  const { token, isLoading: isAuthLoading } = useAuth();
  const [form, setForm] = useState<BlogForm>(() => ({
    ...initialForm,
    published_at: formatDateForApi(new Date()),
  }));
  const [categories, setCategories] = useState<BlogCategory[]>([]);
  const [isCategoriesLoading, setIsCategoriesLoading] = useState(true);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [action, setAction] = useState<BlogStatus>("draft");
  const [bannerPreviewUrl, setBannerPreviewUrl] = useState("");
  const autoFilledFields = useRef({
    meta_title: "",
    meta_description: "",
    og_title: "",
    og_description: "",
  });

  useEffect(() => {
    if (!form.banner_image) {
      setBannerPreviewUrl("");
      return;
    }

    const nextPreviewUrl = URL.createObjectURL(form.banner_image);
    setBannerPreviewUrl(nextPreviewUrl);

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

  useEffect(() => {
    const nextTitle = form.title.trim();
    const previousAuto = autoFilledFields.current;

    setForm((current) => {
      const shouldSetMetaTitle =
        !current.meta_title || current.meta_title === previousAuto.meta_title;
      const shouldSetOgTitle =
        !current.og_title || current.og_title === previousAuto.og_title;

      if (!shouldSetMetaTitle && !shouldSetOgTitle) {
        return current;
      }

      return {
        ...current,
        meta_title: shouldSetMetaTitle ? nextTitle : current.meta_title,
        og_title: shouldSetOgTitle ? nextTitle : current.og_title,
      };
    });

    autoFilledFields.current.meta_title = nextTitle;
    autoFilledFields.current.og_title = nextTitle;
  }, [form.title]);

  useEffect(() => {
    const nextDescription = makeSeoDescription(form.content);
    const previousAuto = autoFilledFields.current;

    setForm((current) => {
      const shouldSetMetaDescription =
        !current.meta_description ||
        current.meta_description === previousAuto.meta_description;
      const shouldSetOgDescription =
        !current.og_description ||
        current.og_description === previousAuto.og_description;

      if (!shouldSetMetaDescription && !shouldSetOgDescription) {
        return current;
      }

      return {
        ...current,
        meta_description: shouldSetMetaDescription
          ? nextDescription
          : current.meta_description,
        og_description: shouldSetOgDescription
          ? nextDescription
          : current.og_description,
      };
    });

    autoFilledFields.current.meta_description = nextDescription;
    autoFilledFields.current.og_description = nextDescription;
  }, [form.content]);

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

    let isMounted = true;

    async function fetchCategories() {
      setIsCategoriesLoading(true);

      try {
        const activeToken =
          token ||
          (typeof window !== "undefined"
            ? localStorage.getItem("auth_token")
            : null);
        const response = await apiRequest(apiUrl("/blog-categories"), {
          headers: {
            ...(activeToken ? { Authorization: `Bearer ${activeToken}` } : {}),
            Accept: "application/json",
          },
        });
        const result = (await response.json()) as BlogCategoriesApiResponse;

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

        const nextCategories = getApiCategoryList(result)
          .map(mapBlogCategory)
          .filter((category): category is BlogCategory => Boolean(category));

        if (isMounted) {
          setCategories(nextCategories);
        }
      } catch (error) {
        if (isMounted) {
          setCategories([]);
          toast.error(
            error instanceof Error
              ? error.message
              : "Failed to load blog categories.",
          );
        }
      } finally {
        if (isMounted) {
          setIsCategoriesLoading(false);
        }
      }
    }

    fetchCategories();

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

  useEffect(() => {
    if (isCategoriesLoading) {
      return;
    }

    const availableCategoryUuids = new Set(
      categories.map((category) => category.uuid),
    );

    setForm((current) => {
      const nextCategoryUuids = current.category_uuids.filter(
        (uuid) => isUuid(uuid) && availableCategoryUuids.has(uuid),
      );

      if (nextCategoryUuids.length === current.category_uuids.length) {
        return current;
      }

      return {
        ...current,
        category_uuids: nextCategoryUuids,
      };
    });
  }, [categories, isCategoriesLoading]);

  const selectedCategoryLabels = useMemo(
    () =>
      categories
        .filter((category) => form.category_uuids.includes(category.uuid))
        .map((category) => category.title),
    [categories, form.category_uuids],
  );
  const generatedSlug = useMemo(() => makeSlug(form.title), [form.title]);
  const calculatedReadTimeMinutes = useMemo(
    () => calculateReadTimeMinutes(form.content),
    [form.content],
  );
  const calculatedReadTimeLabel = calculatedReadTimeMinutes
    ? `${calculatedReadTimeMinutes} min read`
    : "";

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

  const toggleCategory = (uuid: string) => {
    setForm((current) => {
      const selected = current.category_uuids;

      return {
        ...current,
        category_uuids: selected.includes(uuid)
          ? selected.filter((item) => item !== uuid)
          : [...selected, uuid],
      };
    });
  };

  const appendFiles = (
    field: "media_images" | "media_videos",
    files: FileList | null,
  ) => {
    if (!files?.length) {
      return;
    }

    const nextFiles = Array.from(files);
    const invalidFile = nextFiles.find((file) => validateMediaFile(file));

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

    setForm((current) => ({
      ...current,
      [field]: [...current[field], ...nextFiles],
    }));
  };

  const removeFile = (
    field: "media_images" | "media_videos",
    index: number,
  ) => {
    setForm((current) => ({
      ...current,
      [field]: current[field].filter((_, itemIndex) => itemIndex !== index),
    }));
  };

  const handleSubmit = async (submitAction: BlogStatus) => {
    const requestStatus = getBlogRequestStatus(submitAction);
    setAction(submitAction);
    setForm((current) => ({ ...current, status: requestStatus }));
    setIsSubmitting(true);

    try {
      const media = [...form.media_images, ...form.media_videos];
      const validationErrors = validateBlogForm({
        ...form,
        slug: generatedSlug,
        read_time: calculatedReadTimeMinutes,
        media,
      });
      const firstValidationError = getFirstValidationError(validationErrors);

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

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

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

      const payload = new FormData();
      payload.append("title", form.title.trim());
      payload.append("title_hi", form.title_hi.trim());
      payload.append("slug", generatedSlug);
      payload.append("content", form.content.trim());
      payload.append("content_hi", form.content_hi.trim());
      payload.append("read_time", String(calculatedReadTimeMinutes));
      payload.append("status", requestStatus);
      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());
      form.category_uuids.filter(isUuid).forEach((uuid) => {
        payload.append("category_uuids[]", uuid);
      });
      if (form.banner_image) {
        payload.append("banner_image", form.banner_image);
      }
      form.media_images.forEach((file) => {
        payload.append("media[]", file);
      });
      form.media_videos.forEach((file) => {
        payload.append("media[]", file);
      });

      const response = await apiRequest(apiUrl("/admin/blogs"), {
        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 post save failed."));
        return;
      }

      toast.success(getLocalizedApiMessage(result, "Blog post saved."));
      router.push("/admin/blogs");
    } catch {
      toast.error("Unable to connect to the blog server.");
    } finally {
      setIsSubmitting(false);
    }
  };

  const isValid =
    Boolean(form.title.trim()) &&
    Boolean(form.content.trim()) &&
    form.category_uuids.length > 0;

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

      <div className="flex items-center gap-4 rounded-3xl border border-[var(--theme-border)] bg-white p-5 shadow-sm">
        <Link href="/admin/blogs">
          <Button variant="outline" size="icon" className="rounded-full">
            <ArrowLeft className="h-5 w-5" />
          </Button>
        </Link>
        <div>
          <h1 className="text-2xl font-black text-foreground">New Blog Post</h1>
          <p className="mt-1 text-sm font-medium text-muted-foreground">
            Create a searchable travel story with categories, media, and SEO.
          </p>
        </div>
      </div>

      <Alert className="rounded-2xl border-blue-200 bg-blue-50">
        <Info className="h-4 w-4 text-blue-700" />
        <AlertDescription className="font-medium text-blue-900">
          Your blog post will be reviewed by the admin team before it appears on
          the public website.
        </AlertDescription>
      </Alert>

      <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)]">
          {bannerPreviewUrl ? (
            <img
              src={bannerPreviewUrl}
              alt="Blog banner preview"
              className="h-full w-full object-cover"
            />
          ) : (
            <div className="text-center">
              <FileImage className="mx-auto h-12 w-12 text-[var(--theme-primary)]" />
              <p className="mt-3 text-sm font-black text-foreground">
                Banner image preview
              </p>
              <p className="mt-1 text-xs font-medium text-muted-foreground">
                Upload a wide image that represents the blog.
              </p>
            </div>
          )}
          <div className="absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/55 to-transparent p-5">
            <div className="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
              <div className="text-white">
                <p className="text-xs font-black uppercase tracking-wide text-white/75">
                  Banner Image
                </p>
                <p className="mt-1 text-lg font-black">
                  {form.banner_image?.name || "No banner selected"}
                </p>
              </div>
              <div className="flex gap-2">
                <Label
                  htmlFor="blog-banner"
                  className="inline-flex h-11 cursor-pointer items-center justify-center rounded-xl bg-white px-4 text-sm font-black text-[var(--theme-emphasis-text)] shadow-sm hover:bg-[var(--theme-surface-strong)]"
                >
                  Choose Image
                </Label>
                {form.banner_image && (
                  <Button
                    type="button"
                    variant="outline"
                    className="h-11 rounded-xl border-white/40 bg-black/20 text-white hover:bg-black/35 hover:text-white"
                    onClick={() => setField("banner_image", null)}
                  >
                    <Trash2 className="mr-2 h-4 w-4" />
                    Remove
                  </Button>
                )}
              </div>
            </div>
          </div>
          <Input
            id="blog-banner"
            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;
              }

              setField("banner_image", file);
            }}
            className="sr-only"
          />
        </div>
      </Card>

      <div className="grid gap-5">
        <div 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="flex items-center gap-2 text-xl font-black">
                <BookOpen className="h-5 w-5 text-[var(--theme-primary)]" />
                Blog Content
              </CardTitle>
              <CardDescription>
                Write the main story and Hindi translation.
              </CardDescription>
            </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" required>
                    Title
                  </FieldLabel>
                  <Input
                    id="blog-title"
                    value={form.title}
                    onChange={(event) => setField("title", event.target.value)}
                    placeholder="Best treks near Chopta"
                    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">
                  <div className="space-y-1">
                    <FieldLabel>Read Time</FieldLabel>
                    <p className="flex items-start gap-1.5 text-xs font-semibold italic text-[var(--theme-primary)]">
                      <CircleHelp className="mt-0.5 h-3.5 w-3.5 shrink-0" />
                      <span>
                        Estimated time a visitor needs to read the blog content.
                      </span>
                    </p>
                  </div>
                  <div className="flex h-11 items-center rounded-xl border border-[var(--theme-border-soft)] bg-[var(--theme-surface)] px-3 text-sm font-medium text-muted-foreground">
                    {calculatedReadTimeLabel || "Calculated from content"}
                  </div>
                </div>

                <div className="space-y-2">
                  <div className="space-y-1">
                    <FieldLabel htmlFor="published-at">Published At</FieldLabel>
                    <p className="flex items-start gap-1.5 text-xs font-semibold italic text-[var(--theme-primary)]">
                      <CircleHelp className="mt-0.5 h-3.5 w-3.5 shrink-0" />
                      <span>
                        Used as the blog publish date on listings and detail
                        pages.
                      </span>
                    </p>
                  </div>
                  <DatePickerInput
                    id="published-at"
                    value={form.published_at}
                    onValueChange={(value) => setField("published_at", value)}
                  />
                </div>
              </div>

              <div className="space-y-2">
                <FieldLabel htmlFor="blog-content" required>
                  Content
                </FieldLabel>
                <RichTextEditor
                  id="blog-content"
                  value={form.content}
                  onChange={(value) => setField("content", value)}
                  placeholder="Write route details, best season, permits, safety notes, local tips, and itinerary suggestions..."
                />
              </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)}
                  placeholder="Write Hindi blog content..."
                  minHeightClassName="min-h-[220px]"
                />
              </div>
            </CardContent>
          </Card>
        </div>
      </div>

      <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)]" />
            Categories
          </CardTitle>
          <CardDescription>Select one or more blog categories.</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4 p-5 pt-2">
          <div>
            {isCategoriesLoading && (
              <div className="col-span-full flex min-h-20 items-center justify-center rounded-xl border border-dashed border-[var(--theme-border-soft)] bg-[var(--theme-surface)] text-sm font-semibold text-muted-foreground">
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                Loading blog categories...
              </div>
            )}

            {!isCategoriesLoading && (
              <BlogCategorySelection
                categories={categories}
                selectedUuids={form.category_uuids}
                onToggle={toggleCategory}
              />
            )}
          </div>

          {selectedCategoryLabels.length > 0 && (
            <div className="flex flex-wrap gap-2">
              {selectedCategoryLabels.map((label) => (
                <Badge
                  key={label}
                  className="rounded-full bg-[var(--theme-surface-strong)] text-[var(--theme-emphasis-text)]"
                >
                  {label}
                </Badge>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      <Accordion type="single" collapsible className="space-y-5">
        <AccordionItem
          value="blog-media"
          className="overflow-hidden rounded-3xl border border-[var(--theme-border)] bg-white shadow-sm"
        >
          <AccordionTrigger className="px-5 py-5 hover:no-underline">
            <div className="text-left">
              <div className="flex items-center gap-2 text-xl font-black">
                <FileImage className="h-5 w-5 text-[var(--theme-primary)]" />
                Blog Media
              </div>
              <p className="mt-1 text-sm font-normal text-muted-foreground">
                Upload supporting images and videos.
              </p>
            </div>
          </AccordionTrigger>
          <AccordionContent className="px-5 pb-5">
            <div className="mb-4 rounded-2xl border border-blue-200 bg-blue-50 p-4 text-sm font-medium leading-6 text-blue-900">
              <div className="mb-1 flex items-center gap-2 font-black text-blue-950">
                <FileVideo className="h-4 w-4" />
                What blog media is used for
              </div>
              Add supporting photos, PDFs, and videos that can appear inside the
              blog gallery or content sections. These files are sent as media[].
            </div>
            <div className="grid gap-4 md:grid-cols-2">
              <div className="rounded-2xl border border-[var(--theme-border-soft)] bg-white p-4">
                <FieldLabel htmlFor="blog-media-images">
                  Multiple Images / PDFs
                </FieldLabel>
                <Input
                  id="blog-media-images"
                  type="file"
                  accept="image/jpeg,image/png,image/webp,application/pdf"
                  multiple
                  onChange={(event) => {
                    appendFiles("media_images", event.target.files);
                    event.target.value = "";
                  }}
                  className="mt-2 h-11 rounded-xl border-[var(--theme-border-soft)] bg-[var(--theme-surface)]"
                />
                <FileList
                  files={form.media_images}
                  onRemove={(index) => removeFile("media_images", index)}
                />
              </div>

              <div className="rounded-2xl border border-[var(--theme-border-soft)] bg-white p-4">
                <FieldLabel htmlFor="blog-media-videos">
                  Multiple Videos
                </FieldLabel>
                <Input
                  id="blog-media-videos"
                  type="file"
                  accept="video/mp4,video/quicktime,video/x-msvideo"
                  multiple
                  onChange={(event) => {
                    appendFiles("media_videos", event.target.files);
                    event.target.value = "";
                  }}
                  className="mt-2 h-11 rounded-xl border-[var(--theme-border-soft)] bg-[var(--theme-surface)]"
                />
                <FileList
                  files={form.media_videos}
                  onRemove={(index) => removeFile("media_videos", index)}
                />
              </div>
            </div>
          </AccordionContent>
        </AccordionItem>

        <AccordionItem
          value="seo-data"
          className="overflow-hidden rounded-3xl border border-[var(--theme-border)] bg-white shadow-sm"
        >
          <AccordionTrigger className="px-5 py-5 hover:no-underline">
            <div className="text-left">
              <div className="flex items-center gap-2 text-xl font-black">
                <Search className="h-5 w-5 text-[var(--theme-primary)]" />
                SEO Data
              </div>
              <p className="mt-1 text-sm font-normal text-muted-foreground">
                Control search metadata.
              </p>
            </div>
          </AccordionTrigger>
          <AccordionContent className="space-y-5 px-5 pb-5">
            <div className="rounded-2xl border border-blue-200 bg-blue-50 p-4 text-sm font-medium leading-6 text-blue-900">
              <div className="mb-1 flex items-center gap-2 font-black text-blue-950">
                <Search className="h-4 w-4" />
                What SEO data is used for
              </div>
              SEO fields help search engines understand this blog page. Meta
              title and description can appear in search results, and keywords
              help describe the topic.
            </div>
            <div className="grid gap-4 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)
                  }
                  placeholder="trekking, chopta, uttarakhand"
                  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>
            </div>
          </AccordionContent>
        </AccordionItem>

        <AccordionItem
          value="open-graph"
          className="overflow-hidden rounded-3xl border border-[var(--theme-border)] bg-white shadow-sm"
        >
          <AccordionTrigger className="px-5 py-5 hover:no-underline">
            <div className="text-left">
              <div className="flex items-center gap-2 text-xl font-black">
                <Globe2 className="h-5 w-5 text-[var(--theme-primary)]" />
                Open Graph
              </div>
              <p className="mt-1 text-sm font-normal text-muted-foreground">
                Set social sharing previews.
              </p>
            </div>
          </AccordionTrigger>
          <AccordionContent className="px-5 pb-5">
            <div className="mb-4 rounded-2xl border border-blue-200 bg-blue-50 p-4 text-sm font-medium leading-6 text-blue-900">
              <div className="mb-1 flex items-center gap-2 font-black text-blue-950">
                <Globe2 className="h-4 w-4" />
                What Open Graph is used for
              </div>
              Open Graph controls the title and description shown when the blog
              is shared on social platforms and messaging apps.
            </div>
            <div className="grid gap-4 md:grid-cols-2">
              <div className="space-y-2 md:col-span-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 md:col-span-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>
            </div>
          </AccordionContent>
        </AccordionItem>
      </Accordion>

      <div className="flex flex-col-reverse gap-3 rounded-3xl border border-[var(--theme-border)] bg-white p-5 shadow-sm sm:flex-row sm:items-center sm:justify-end">
        {!isValid && (
          <p className="text-sm font-medium text-muted-foreground sm:mr-auto">
            Save as Draft to keep working later, or Publish when the blog is
            complete and ready for review.
          </p>
        )}
        <Link href="/admin/blogs">
          <Button type="button" variant="outline" className="h-11 rounded-xl">
            Cancel
          </Button>
        </Link>
        <Button
          type="button"
          variant="secondary"
          className="h-11 rounded-xl"
          onClick={() => handleSubmit("draft")}
          disabled={!isValid || isSubmitting}
        >
          {isSubmitting && action === "draft" ? (
            <Loader2 className="mr-2 h-4 w-4 animate-spin" />
          ) : (
            <Save className="mr-2 h-4 w-4" />
          )}
          Save as Draft
        </Button>
        <Button
          type="button"
          className="h-11 rounded-xl bg-[var(--theme-primary)] hover:bg-[var(--theme-accent-dark)]"
          onClick={() => handleSubmit("submitted")}
          disabled={!isValid || isSubmitting}
        >
          {isSubmitting && action === "submitted" ? (
            <Loader2 className="mr-2 h-4 w-4 animate-spin" />
          ) : (
            <Send className="mr-2 h-4 w-4" />
          )}
          Submit for Review
        </Button>
      </div>
    </div>
  );
}
