"use client";

import { cn, getStorageUrl } from "@/lib/utils";
import { zodResolver } from "@hookform/resolvers/zod";
import {
  ArrowLeft,
  Eye,
  Loader2,
  Monitor,
  RefreshCw,
  Save,
  Smartphone,
  Tablet,
  Trash2,
  Upload,
} from "lucide-react";
import { useRouter } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import { useForm } from "react-hook-form";

import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import type { Banner } from "@/features/banners/api";
import {
  createBannerAction,
  getBannerAction,
  updateBannerAction,
} from "@/features/banners/api";
import { useToastEnhanced } from "@/hooks/use-toast-enhanced";
import { BANNERS_ADMIN } from "@/lib/strings/banners-admin";
import { bannerSchema, type BannerInput } from "@/lib/validations/banner";
import { BannerPreview } from "./banner-preview";

// ─── Image URL helper ──────────────────────────────────────────────────────────

function getImageUrl(path: string | null | undefined): string {
  if (!path) return "";
  if (path.startsWith("http")) return path;
  return `${getStorageUrl(path)}`;
}

// ─── Types ─────────────────────────────────────────────────────────────────────

interface ImagePreviews {
  desktop: string | null;
  tablet: string | null;
  mobile: string | null;
}

interface ImageFiles {
  desktop: File | null;
  tablet: File | null;
  mobile: File | null;
}

interface Props {
  /** When provided, component is in edit mode (load + update). When undefined, add mode (create). */
  bannerId?: string;
}

// ─── Component ─────────────────────────────────────────────────────────────────

export function EditBannerClient({ bannerId }: Props) {
  const router = useRouter();
  const toast = useToastEnhanced();
  const formRef = useRef<HTMLButtonElement>(null);
  const isEditMode = bannerId != null;

  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isLoading, setIsLoading] = useState(isEditMode);
  const [loadError, setLoadError] = useState<string | null>(null);
  const [showPreview, setShowPreview] = useState(true);
  const [previewView, setPreviewView] = useState<
    "desktop" | "tablet" | "mobile"
  >("desktop");
  const [originalBanner, setOriginalBanner] = useState<Banner | null>(null);

  // Separate preview URLs (blob for new, API URL for existing)
  const [imagePreviews, setImagePreviews] = useState<ImagePreviews>({
    desktop: null,
    tablet: null,
    mobile: null,
  });

  // Track new File objects selected by the user
  const [imageFiles, setImageFiles] = useState<ImageFiles>({
    desktop: null,
    tablet: null,
    mobile: null,
  });

  const {
    register,
    handleSubmit,
    setValue,
    watch,
    reset,
    formState: { errors },
  } = useForm<BannerInput>({
    resolver: zodResolver(bannerSchema) as any,
    defaultValues: {
      title: "",
      subtitle: "",
      description: "",
      sort_order: 0,
      status: true,
      primary_button_text: "",
      primary_button_url: "",
      secondary_button_text: "",
      secondary_button_url: "",
    } as any,
  });

  const watchedFields = watch();

  // ── Load existing banner via GET /api/banners/{id} (edit mode only) ───────────
  useEffect(() => {
    if (!isEditMode || !bannerId) {
      setIsLoading(false);
      return;
    }
    async function loadBanner() {
      setIsLoading(true);
      setLoadError(null);
      try {
        const result = await getBannerAction(bannerId!);
        if (!result.success || !result.data) {
          setLoadError(result.error ?? BANNERS_ADMIN.BANNER_NOT_FOUND);
          return;
        }
        const b = result.data;
        setOriginalBanner(b);

        // Pre-fill the form
        reset({
          title: b.title,
          subtitle: b.subtitle ?? "",
          description: b.description ?? "",
          sort_order: b.sort_order,
          status: b.status === "active",
          primary_button_text: b.primary_button_text ?? "",
          primary_button_url: b.primary_button_url ?? "",
          secondary_button_text: b.secondary_button_text ?? "",
          secondary_button_url: b.secondary_button_url ?? "",
          // existing images are pre-filled as a marker; actual File is null
          desktop_image: b.desktop_image ? "existing" : undefined,
          tablet_image: b.tablet_image ? "existing" : undefined,
          mobile_image: b.mobile_image ? "existing" : undefined,
        } as any);

        // Set preview URLs to existing API images
        setImagePreviews({
          desktop: getImageUrl(b.desktop_image),
          tablet: getImageUrl(b.tablet_image),
          mobile: getImageUrl(b.mobile_image),
        });
      } catch {
        setLoadError(BANNERS_ADMIN.FAILED_LOAD_BANNER_DATA);
      } finally {
        setIsLoading(false);
      }
    }
    loadBanner();
  }, [isEditMode, bannerId, reset]);

  // ── File handlers ─────────────────────────────────────────────────────────────

  const handleFileChange = (
    e: React.ChangeEvent<HTMLInputElement>,
    type: keyof ImageFiles
  ) => {
    const file = e.target.files?.[0];
    if (file) {
      const url = URL.createObjectURL(file);
      setImagePreviews((prev) => ({ ...prev, [type]: url }));
      setImageFiles((prev) => ({ ...prev, [type]: file }));
      setValue(`${type}_image` as any, file, { shouldValidate: true });
    }
  };

  const removeImage = (type: keyof ImageFiles) => {
    setImagePreviews((prev) => ({ ...prev, [type]: null }));
    setImageFiles((prev) => ({ ...prev, [type]: null }));
    setValue(`${type}_image` as any, null, { shouldValidate: true });
  };

  // Cleanup blob URLs on unmount
  useEffect(() => {
    return () => {
      Object.values(imageFiles).forEach((url) => {
        if (url) URL.revokeObjectURL(URL.createObjectURL(url));
      });
    };
  }, []);

  // ── Submit ────────────────────────────────────────────────────────────────────

  const onSubmit = async (data: BannerInput) => {
    setIsSubmitting(true);
    try {
      if (isEditMode && bannerId) {
        const result = await updateBannerAction(bannerId, {
          title: data.title,
          subtitle: data.subtitle ?? undefined,
          description: data.description ?? undefined,
          desktop_image:
            imageFiles.desktop || originalBanner?.desktop_image || undefined,
          tablet_image:
            imageFiles.tablet || originalBanner?.tablet_image || undefined,
          mobile_image:
            imageFiles.mobile || originalBanner?.mobile_image || undefined,
          primary_button_text: data.primary_button_text ?? undefined,
          primary_button_url: data.primary_button_url ?? undefined,
          secondary_button_text: data.secondary_button_text ?? undefined,
          secondary_button_url: data.secondary_button_url ?? undefined,
          sort_order: data.sort_order ?? 0,
          status: data.status ? "active" : "inactive",
        });
        if (result.success) {
          toast.success({
            title: BANNERS_ADMIN.BANNER_UPDATED,
            description: BANNERS_ADMIN.BANNER_UPDATED_DESCRIPTION,
          });
          router.push("/admin/banners");
        } else {
          toast.error({
            title: BANNERS_ADMIN.UPDATE_FAILED,
            description:
              result.error ?? BANNERS_ADMIN.UPDATE_FAILED_DESCRIPTION,
          });
        }
      } else {
        const result = await createBannerAction({
          title: data.title,
          subtitle: data.subtitle ?? undefined,
          description: data.description ?? undefined,
          desktop_image: imageFiles.desktop ?? undefined,
          tablet_image: imageFiles.tablet ?? undefined,
          mobile_image: imageFiles.mobile ?? undefined,
          primary_button_text: data.primary_button_text ?? undefined,
          primary_button_url: data.primary_button_url ?? undefined,
          secondary_button_text: data.secondary_button_text ?? undefined,
          secondary_button_url: data.secondary_button_url ?? undefined,
          sort_order: data.sort_order ?? 0,
          status: data.status ? "active" : "inactive",
        });
        if (result.success) {
          toast.success({
            title: BANNERS_ADMIN.BANNER_CREATED,
            description: BANNERS_ADMIN.BANNER_CREATED_DESCRIPTION,
          });
          router.push("/admin/banners");
        } else {
          toast.error({
            title: BANNERS_ADMIN.SAVE_FAILED,
            description:
              result.error ?? BANNERS_ADMIN.SAVE_FAILED_CREATE_DESCRIPTION,
          });
        }
      }
    } catch {
      toast.error({
        title: isEditMode
          ? BANNERS_ADMIN.UPDATE_FAILED
          : BANNERS_ADMIN.SAVE_FAILED,
        description: BANNERS_ADMIN.UNEXPECTED_ERROR,
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  // ── Loading State ─────────────────────────────────────────────────────────────

  if (isLoading) {
    return (
      <section className="admin-section space-y-6 max-w-7xl mx-auto">
        <div className="flex items-center gap-4 pb-6 border-b">
          <Button
            variant="ghost"
            size="icon"
            onClick={() => router.back()}
            className="rounded-full"
          >
            <ArrowLeft className="h-5 w-5" />
          </Button>
          <div className="space-y-1.5">
            <div className="h-7 w-48 bg-muted rounded-lg animate-pulse" />
            <div className="h-4 w-72 bg-muted rounded animate-pulse" />
          </div>
        </div>
        <div className="h-[600px] w-full rounded-xl bg-muted/30 animate-pulse" />
      </section>
    );
  }

  if (loadError) {
    return (
      <section className="admin-section max-w-7xl mx-auto flex flex-col items-center justify-center min-h-[400px] gap-4">
        <div className="text-center space-y-2">
          <h2 className="text-2xl font-bold text-destructive">
            {BANNERS_ADMIN.FAILED_TO_LOAD_BANNER}
          </h2>
          <p className="text-muted-foreground">{loadError}</p>
        </div>
        <div className="flex gap-3">
          <Button variant="outline" onClick={() => router.back()}>
            <ArrowLeft className="h-4 w-4 mr-2" /> {BANNERS_ADMIN.GO_BACK}
          </Button>
          <Button onClick={() => window.location.reload()}>
            <RefreshCw className="h-4 w-4 mr-2" /> {BANNERS_ADMIN.RETRY}
          </Button>
        </div>
      </section>
    );
  }

  // ── Main Render ───────────────────────────────────────────────────────────────

  return (
    <section className="admin-section space-y-8 max-w-7xl mx-auto">
      {/* Page Header */}
      <header className="admin-page-header flex flex-col md:flex-row md:items-center justify-between gap-6 sticky top-0 bg-background/80 backdrop-blur-md z-30">
        <div className="flex items-center gap-4">
          <Button
            variant="ghost"
            size="icon"
            onClick={() => router.back()}
            className="rounded-full hover:bg-muted"
          >
            <ArrowLeft className="h-5 w-5" />
          </Button>
          <div>
            <h1 className="admin-page-title text-3xl font-bold tracking-tight">
              {isEditMode
                ? BANNERS_ADMIN.EDIT_BANNER
                : BANNERS_ADMIN.CREATE_BANNER}
            </h1>
            <p className="admin-page-description text-muted-foreground mt-1">
              {isEditMode && originalBanner?.title ? (
                <span>
                  {BANNERS_ADMIN.EDITING_PREFIX}
                  <span className="font-medium text-foreground">
                    {originalBanner.title}
                  </span>
                </span>
              ) : isEditMode ? (
                BANNERS_ADMIN.DESCRIPTION_EDIT
              ) : (
                BANNERS_ADMIN.DESCRIPTION_CREATE
              )}
            </p>
          </div>
        </div>
        <div className="flex items-center gap-3">
          <Button
            variant="outline"
            size="sm"
            className="gap-2 rounded-xl"
            onClick={() => setShowPreview(!showPreview)}
          >
            <Eye className="h-4 w-4" />
            {showPreview
              ? BANNERS_ADMIN.HIDE_PREVIEW
              : BANNERS_ADMIN.SHOW_PREVIEW}
          </Button>
        </div>
      </header>

      {/* Preview - same card structure and styling as Choose Banner */}
      {showPreview && (
        <Card className="admin-card w-full rounded-xl border-0 overflow-hidden mb-6 [background:var(--admin-glass-bg)] [box-shadow:var(--admin-card-shadow)]">
          <CardHeader className="pb-4 flex flex-row flex-wrap items-start justify-between gap-4">
            <div className="space-y-2">
              <CardTitle className="text-xl">{BANNERS_ADMIN.PREVIEW}</CardTitle>
              <CardDescription className="text-xs">
                {BANNERS_ADMIN.PREVIEW_DESCRIPTION}
              </CardDescription>
            </div>
            <div className="flex items-center gap-1 bg-muted/30 p-1 rounded-xl">
              <Button
                variant={previewView === "desktop" ? "secondary" : "ghost"}
                size="sm"
                className="h-7 w-7 p-0 rounded-md"
                onClick={() => setPreviewView("desktop")}
                title={BANNERS_ADMIN.DESKTOP_VIEW}
              >
                <Monitor className="h-3.5 w-3.5" />
              </Button>
              <Button
                variant={previewView === "tablet" ? "secondary" : "ghost"}
                size="sm"
                className="h-7 w-7 p-0 rounded-md"
                onClick={() => setPreviewView("tablet")}
                title={BANNERS_ADMIN.TABLET_VIEW}
              >
                <Tablet className="h-3.5 w-3.5" />
              </Button>
              <Button
                variant={previewView === "mobile" ? "secondary" : "ghost"}
                size="sm"
                className="h-7 w-7 p-0 rounded-md"
                onClick={() => setPreviewView("mobile")}
                title={BANNERS_ADMIN.MOBILE_VIEW}
              >
                <Smartphone className="h-3.5 w-3.5" />
              </Button>
            </div>
          </CardHeader>
          <CardContent>
            <BannerPreview
              data={{
                ...watchedFields,
                desktop_image: imagePreviews.desktop,
                tablet_image: imagePreviews.tablet,
                mobile_image: imagePreviews.mobile,
              }}
              activeView={previewView}
              onViewChange={setPreviewView}
              showPlacementHints={!isEditMode}
            />
          </CardContent>
        </Card>
      )}

      {/* Form Panel - no horizontal padding so card widths match Preview card */}
      <form
        onSubmit={handleSubmit(onSubmit)}
        className="py-5 space-y-8 flex-1 overflow-y-auto w-full"
      >
        {/* Choose Banner - first */}
        <Card className="admin-card w-full rounded-xl border-0 overflow-hidden [background:var(--admin-glass-bg)] [box-shadow:var(--admin-card-shadow)]">
          <CardHeader className="pb-4">
            <CardTitle className="text-xl">
              {BANNERS_ADMIN.CHOOSE_BANNER}
            </CardTitle>
            <CardDescription className="text-xs">
              {isEditMode
                ? BANNERS_ADMIN.CHOOSE_BANNER_DESCRIPTION_EDIT
                : BANNERS_ADMIN.CHOOSE_BANNER_DESCRIPTION_CREATE}
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-12 gap-6">
              {/* Desktop - 4/12 */}
              <div className="col-span-12 md:col-span-4 space-y-3">
                <Label className="text-sm font-semibold flex items-center gap-2">
                  <Monitor className="h-4 w-4 text-primary" />
                  {BANNERS_ADMIN.DESKTOP}{" "}
                  <span className="text-[10px] text-muted-foreground font-normal">
                    {BANNERS_ADMIN.DESKTOP_SIZE}
                  </span>
                </Label>

                {imagePreviews.desktop ? (
                  <div className="relative rounded-xl overflow-hidden h-[200px] border border-border group shadow-sm">
                    <img
                      src={imagePreviews.desktop}
                      className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105"
                      alt={BANNERS_ADMIN.DESKTOP}
                    />
                    <div className="absolute inset-0 bg-black/60 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center backdrop-blur-sm gap-2">
                      <Button
                        type="button"
                        variant="secondary"
                        size="sm"
                        className="rounded-xl shadow-xl"
                        onClick={() =>
                          document
                            .getElementById("desktop-upload-edit")
                            ?.click()
                        }
                      >
                        {BANNERS_ADMIN.REPLACE}
                      </Button>
                      <Button
                        type="button"
                        variant="destructive"
                        size="sm"
                        className="h-8 w-8 p-0 rounded-full shadow-xl"
                        onClick={() => removeImage("desktop")}
                      >
                        <Trash2 className="h-3.5 w-3.5" />
                      </Button>
                    </div>
                  </div>
                ) : (
                  <div
                    onClick={() =>
                      document.getElementById("desktop-upload-edit")?.click()
                    }
                    className={cn(
                      "border-2 border-dashed rounded-xl flex flex-col items-center justify-center h-[200px] bg-muted/5 transition-all duration-200 hover:bg-muted/10 hover:border-primary/50 cursor-pointer group relative",
                      errors.desktop_image &&
                        "border-destructive/50 bg-destructive/5"
                    )}
                  >
                    <div className="h-10 w-10 rounded-xl bg-primary/10 flex items-center justify-center mb-2 group-hover:scale-110 transition-all text-primary">
                      <Upload className="h-4 w-4" />
                    </div>
                    <p className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground group-hover:text-primary text-center px-1">
                      {BANNERS_ADMIN.CHOOSE_IMAGE_DESKTOP}
                    </p>
                  </div>
                )}
                <Input
                  type="file"
                  id="desktop-upload-edit"
                  className="hidden"
                  accept="image/*"
                  onChange={(e) => handleFileChange(e, "desktop")}
                />
                {errors.desktop_image && (
                  <p className="text-xs text-destructive mt-1">
                    {errors.desktop_image.message as string}
                  </p>
                )}
              </div>

              {/* Tablet - 4/12 */}
              <div className="col-span-12 md:col-span-4 space-y-3">
                <Label className="text-sm font-semibold flex items-center gap-2">
                  <Tablet className="h-4 w-4 text-primary" />
                  {BANNERS_ADMIN.TABLET}{" "}
                  <span className="text-[10px] text-muted-foreground font-normal">
                    {BANNERS_ADMIN.TABLET_SIZE}
                  </span>
                </Label>
                {imagePreviews.tablet ? (
                  <div className="relative rounded-xl overflow-hidden h-[200px] group shadow-sm ring-1 ring-border/50">
                    <img
                      src={imagePreviews.tablet}
                      className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-110"
                      alt={BANNERS_ADMIN.TABLET}
                    />
                    <div className="absolute inset-0 bg-black/60 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
                      <Button
                        type="button"
                        variant="secondary"
                        size="sm"
                        className="rounded-xl shadow-xl mr-2"
                        onClick={() =>
                          document.getElementById("tablet-upload-edit")?.click()
                        }
                      >
                        {BANNERS_ADMIN.REPLACE}
                      </Button>
                      <Button
                        type="button"
                        variant="destructive"
                        size="sm"
                        className="h-8 w-8 p-0 rounded-full shadow-xl"
                        onClick={() => removeImage("tablet")}
                      >
                        <Trash2 className="h-3.5 w-3.5" />
                      </Button>
                    </div>
                  </div>
                ) : (
                  <div
                    onClick={() =>
                      document.getElementById("tablet-upload-edit")?.click()
                    }
                    className="border-2 border-dashed rounded-xl flex flex-col items-center justify-center h-[200px] bg-muted/5 hover:bg-muted/10 hover:border-primary/50 transition-all cursor-pointer group relative"
                  >
                    <div className="h-10 w-10 rounded-xl bg-primary/10 flex items-center justify-center mb-2 group-hover:scale-110 transition-all text-primary">
                      <Upload className="h-4 w-4" />
                    </div>
                    <p className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground group-hover:text-primary">
                      {BANNERS_ADMIN.CHOOSE_IMAGE_TABLET}
                    </p>
                  </div>
                )}
                <Input
                  type="file"
                  id="tablet-upload-edit"
                  className="hidden"
                  accept="image/*"
                  onChange={(e) => handleFileChange(e, "tablet")}
                />
              </div>

              {/* Mobile - 4/12 */}
              <div className="col-span-12 md:col-span-4 space-y-3">
                <Label className="text-sm font-semibold flex items-center gap-2">
                  <Smartphone className="h-4 w-4 text-primary" />
                  {BANNERS_ADMIN.MOBILE}{" "}
                  <span className="text-[10px] text-muted-foreground font-normal">
                    {BANNERS_ADMIN.MOBILE_SIZE}
                  </span>
                </Label>
                {imagePreviews.mobile ? (
                  <div className="relative rounded-xl overflow-hidden h-[200px] group shadow-sm ring-1 ring-border/50">
                    <img
                      src={imagePreviews.mobile}
                      className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-110"
                      alt={BANNERS_ADMIN.MOBILE}
                    />
                    <div className="absolute inset-0 bg-black/60 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
                      <Button
                        type="button"
                        variant="secondary"
                        size="sm"
                        className="rounded-xl shadow-xl mr-2"
                        onClick={() =>
                          document.getElementById("mobile-upload-edit")?.click()
                        }
                      >
                        {BANNERS_ADMIN.REPLACE}
                      </Button>
                      <Button
                        type="button"
                        variant="destructive"
                        size="sm"
                        className="h-8 w-8 p-0 rounded-full shadow-xl"
                        onClick={() => removeImage("mobile")}
                      >
                        <Trash2 className="h-3.5 w-3.5" />
                      </Button>
                    </div>
                  </div>
                ) : (
                  <div
                    onClick={() =>
                      document.getElementById("mobile-upload-edit")?.click()
                    }
                    className="border-2 border-dashed rounded-xl flex flex-col items-center justify-center h-[200px] bg-muted/5 hover:bg-muted/10 hover:border-primary/50 transition-all cursor-pointer group relative"
                  >
                    <div className="h-10 w-10 rounded-xl bg-primary/10 flex items-center justify-center mb-2 group-hover:scale-110 transition-all text-primary">
                      <Upload className="h-4 w-4" />
                    </div>
                    <p className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground group-hover:text-primary">
                      {BANNERS_ADMIN.CHOOSE_IMAGE_MOBILE}
                    </p>
                  </div>
                )}
                <Input
                  type="file"
                  id="mobile-upload-edit"
                  className="hidden"
                  accept="image/*"
                  onChange={(e) => handleFileChange(e, "mobile")}
                />
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Information */}
        <Card className="admin-card w-full rounded-xl border-0 gap-y-2 [background:var(--admin-glass-bg)] [box-shadow:var(--admin-card-shadow)]">
          <CardHeader className="pb-2">
            <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
              <CardTitle className="text-xl">
                {BANNERS_ADMIN.INFORMATION}
              </CardTitle>
              <div className="flex flex-wrap items-center gap-4">
                <div className="grid gap-1">
                  <Label htmlFor="sort_order" className="text-xs font-semibold">
                    {BANNERS_ADMIN.SORT_ORDER}
                  </Label>
                  <Input
                    id="sort_order"
                    type="number"
                    {...register("sort_order", { valueAsNumber: true })}
                    className="h-9 w-32 rounded-xl text-xs"
                  />
                </div>
                <div className="grid gap-1">
                  <Label className="text-xs font-semibold">
                    {BANNERS_ADMIN.STATUS}
                  </Label>
                  <Select
                    value={watchedFields.status ? "active" : "inactive"}
                    onValueChange={(val: "active" | "inactive") =>
                      setValue("status", val === "active")
                    }
                  >
                    <SelectTrigger className="h-9 w-32 rounded-xl text-xs">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent className="rounded-xl">
                      <SelectItem value="active">
                        {BANNERS_ADMIN.ACTIVE}
                      </SelectItem>
                      <SelectItem value="inactive">
                        {BANNERS_ADMIN.INACTIVE}
                      </SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </div>
          </CardHeader>
          <CardContent className="space-y-6 pt-0">
            <div className="grid grid-cols-12 gap-4 items-start">
              <div className="col-span-12 sm:col-span-3 space-y-2">
                <Label htmlFor="subtitle" className="text-sm font-semibold">
                  {BANNERS_ADMIN.TAG}
                </Label>
                <Input
                  id="subtitle"
                  placeholder={BANNERS_ADMIN.PLACEHOLDER_SUBTITLE}
                  {...register("subtitle")}
                  className="rounded-xl h-11"
                />
              </div>
              <div className="col-span-12 sm:col-span-9 space-y-2">
                <Label htmlFor="title" className="text-sm font-semibold">
                  {BANNERS_ADMIN.TITLE_REQUIRED}
                </Label>
                <Input
                  id="title"
                  placeholder={BANNERS_ADMIN.PLACEHOLDER_TITLE}
                  {...register("title")}
                  className={cn(
                    "rounded-xl focus-visible:ring-primary h-11",
                    errors.title && "border-destructive"
                  )}
                />
                {errors.title && (
                  <p className="text-xs text-destructive">
                    {errors.title.message}
                  </p>
                )}
              </div>
            </div>

            <div className="space-y-2">
              <Label htmlFor="description" className="text-sm font-semibold">
                {BANNERS_ADMIN.DESCRIPTION}
              </Label>
              <Textarea
                id="description"
                placeholder={BANNERS_ADMIN.PLACEHOLDER_DESCRIPTION}
                className="rounded-xl min-h-[100px] resize-none p-4"
                {...register("description")}
              />
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-6 pt-0">
              <div className="space-y-4">
                <Label className="text-sm font-semibold">
                  {BANNERS_ADMIN.PRIMARY_BUTTON}
                </Label>
                <div className="space-y-4">
                  <div className="space-y-2">
                    <Label
                      htmlFor="primary_button_text"
                      className="text-sm font-semibold"
                    >
                      {BANNERS_ADMIN.BUTTON_TEXT}
                    </Label>
                    <Input
                      id="primary_button_text"
                      placeholder={BANNERS_ADMIN.PLACEHOLDER_PRIMARY_TEXT}
                      {...register("primary_button_text")}
                      className="rounded-xl h-11 bg-background"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label
                      htmlFor="primary_button_url"
                      className="text-sm font-semibold"
                    >
                      {BANNERS_ADMIN.PRIMARY_BUTTON_URL}
                    </Label>
                    <Input
                      id="primary_button_url"
                      placeholder={BANNERS_ADMIN.PLACEHOLDER_URL}
                      {...register("primary_button_url")}
                      className="rounded-xl h-11 bg-background"
                    />
                  </div>
                </div>
              </div>

              <div className="space-y-4">
                <Label className="text-sm font-semibold">
                  {BANNERS_ADMIN.SECONDARY_BUTTON}
                </Label>
                <div className="space-y-4">
                  <div className="space-y-2">
                    <Label
                      htmlFor="secondary_button_text"
                      className="text-sm font-semibold"
                    >
                      {BANNERS_ADMIN.BUTTON_TEXT}
                    </Label>
                    <Input
                      id="secondary_button_text"
                      placeholder={BANNERS_ADMIN.PLACEHOLDER_SECONDARY_TEXT}
                      {...register("secondary_button_text")}
                      className="rounded-xl h-11 bg-background"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label
                      htmlFor="secondary_button_url"
                      className="text-sm font-semibold"
                    >
                      {BANNERS_ADMIN.SECONDARY_BUTTON_URL}
                    </Label>
                    <Input
                      id="secondary_button_url"
                      placeholder={BANNERS_ADMIN.PLACEHOLDER_URL}
                      {...register("secondary_button_url")}
                      className="rounded-xl h-11 bg-background"
                    />
                  </div>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        <div className="flex justify-end gap-4 p-6 border-t bg-background/50 sticky bottom-0 z-10 rounded-b-xl">
          <Button
            type="button"
            variant="outline"
            onClick={() => router.back()}
            className="rounded-xl"
          >
            {BANNERS_ADMIN.CANCEL}
          </Button>
          <Button
            type="submit"
            disabled={isSubmitting}
            className="rounded-xl shadow-lg shadow-primary/20 transition-all active:scale-[0.98]"
          >
            {isSubmitting ? (
              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
            ) : (
              <Save className="mr-2 h-4 w-4" />
            )}
            {isEditMode
              ? BANNERS_ADMIN.SAVE_CHANGES
              : BANNERS_ADMIN.SAVE_BANNER}
          </Button>
        </div>
      </form>
    </section>
  );
}
