"use client";

import { useState, useEffect, useRef } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useRouter } from "next/navigation";
import { cn } from "@/lib/utils";
import { motion, AnimatePresence } from "framer-motion";
import {
  ArrowLeft,
  Save,
  Upload,
  Monitor,
  Tablet,
  Smartphone,
  Trash2,
  ImagePlus,
  Loader2,
  Eye,
  EyeOff,
  X,
  Maximize2,
  MonitorPlay,
} from "lucide-react";

import { Button } from "@/components/ui/button";
// ... (rest of imports)
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Switch } from "@/components/ui/switch";
import { useToastEnhanced } from "@/hooks/use-toast-enhanced";
import { BannerPreview } from "./banner-preview";
import { bannerSchema, type BannerInput } from "@/lib/validations/banner";
import { createBannerAction } from "@/features/banners/api";

export function CreateBannerClient() {
  const router = useRouter();
  const toast = useToastEnhanced();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [showPreview, setShowPreview] = useState(true);
  const formRef = useRef<HTMLButtonElement>(null);
  const [imagePreviews, setImagePreviews] = useState<{
    // ... (rest of state and handlers)
    desktop: string | null;
    tablet: string | null;
    mobile: string | null;
  }>({
    desktop: null,
    tablet: null,
    mobile: null,
  });

  const {
    register,
    handleSubmit,
    setValue,
    watch,
    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();

  // Helper to handle file selection and preview
  const handleFileChange = (
    e: React.ChangeEvent<HTMLInputElement>,
    type: keyof typeof imagePreviews
  ) => {
    const file = e.target.files?.[0];
    if (file) {
      const url = URL.createObjectURL(file);
      setImagePreviews((prev) => ({ ...prev, [type]: url }));
      setValue(`${type}_image` as any, file, { shouldValidate: true });
    }
  };

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

  const onSubmit = async (data: BannerInput) => {
    setIsSubmitting(true);
    try {
      const result = await createBannerAction({
        title: data.title,
        subtitle: data.subtitle ?? undefined,
        description: data.description ?? undefined,
        desktop_image:
          data.desktop_image instanceof File ? data.desktop_image : undefined,
        tablet_image:
          data.tablet_image instanceof File ? data.tablet_image : undefined,
        mobile_image:
          data.mobile_image instanceof File ? data.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: "Banner created",
          description: "Your responsive banner has been created successfully.",
        });
        router.push("/admin/banners");
      } else {
        toast.error({
          title: "Save failed",
          description:
            result.error ?? "There was an error creating the banner.",
        });
      }
    } catch (error) {
      toast.error({
        title: "Save failed",
        description: "An unexpected error occurred. Please try again.",
      });
    } finally {
      setIsSubmitting(false);
    }
  };

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

  return (
    <section className="admin-section space-y-8 max-w-7xl mx-auto">
      <header className="admin-page-header flex flex-col md:flex-row md:items-center justify-between gap-6 pb-6 border-b 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">
              Create Banner
            </h1>
            <p className="admin-page-description text-muted-foreground mt-1">
              Configure responsive banner for desktop, tablet, and mobile
              devices
            </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 ? "Hide Preview" : "Show Preview"}
          </Button>
          <div className="w-px h-6 bg-border mx-1 hidden md:block" />
          <Button
            variant="outline"
            onClick={() => router.back()}
            className="rounded-xl"
          >
            Cancel
          </Button>
          <Button
            className="rounded-xl shadow-lg shadow-primary/20 transition-all active:scale-[0.98]"
            onClick={handleSubmit(onSubmit)}
            disabled={isSubmitting}
          >
            {isSubmitting ? (
              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
            ) : (
              <Save className="mr-2 h-4 w-4" />
            )}
            Save Banner
          </Button>
        </div>
      </header>

      <div className="flex gap-0 rounded-xl border border-border bg-card overflow-hidden min-h-[700px]">
        {/* LEFT PANEL: Form Controls */}
        <div
          className={cn(
            "flex flex-col border-r border-border",
            showPreview ? "w-full lg:w-[60%] xl:w-[55%]" : "w-full"
          )}
        >
          {/* Panel Header like Reference */}
          <div className="flex items-center gap-2 px-5 py-3 border-b border-border bg-muted/30">
            <MonitorPlay className="h-4 w-4 text-primary" />
            <h2 className="text-sm font-semibold">Banner Configuration</h2>
          </div>

          <form
            onSubmit={handleSubmit(onSubmit)}
            className="p-5 space-y-8 flex-1 overflow-y-auto"
          >
            {/* Basic Information */}
            <Card className="rounded-2xl border-none shadow-sm ring-1 ring-border bg-card/50 backdrop-blur-sm transition-all duration-300 hover:ring-primary/20">
              <CardHeader className="pb-4">
                <CardTitle className="text-xl">Basic Information</CardTitle>
              </CardHeader>
              <CardContent className="space-y-6">
                <div className="space-y-2">
                  <Label htmlFor="title" className="text-sm font-semibold">
                    Title (Required)
                  </Label>
                  <Input
                    id="title"
                    placeholder="Enter banner 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 className="space-y-2">
                  <Label htmlFor="subtitle" className="text-sm font-semibold">
                    Subtitle
                  </Label>
                  <Input
                    id="subtitle"
                    placeholder="Enter banner subtitle"
                    {...register("subtitle")}
                    className="rounded-xl h-11"
                  />
                </div>

                <div className="space-y-2">
                  <Label
                    htmlFor="description"
                    className="text-sm font-semibold"
                  >
                    Description
                  </Label>
                  <Textarea
                    id="description"
                    placeholder="Enter banner 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-4 pt-2">
                  <div className="space-y-2">
                    <Label
                      htmlFor="sort_order"
                      className="text-sm font-semibold"
                    >
                      Sort Order
                    </Label>
                    <Input
                      id="sort_order"
                      type="number"
                      {...register("sort_order", { valueAsNumber: true })}
                      className="rounded-xl h-11"
                    />
                  </div>
                  <div className="flex items-center justify-between p-3 rounded-xl border bg-muted/20 h-11">
                    <div className="space-y-0.5">
                      <Label className="text-sm font-semibold">Status</Label>
                      <p className="text-[10px] text-muted-foreground uppercase tracking-widest font-bold">
                        {watchedFields.status ? "Enabled" : "Disabled"}
                      </p>
                    </div>
                    <Switch
                      checked={watchedFields.status}
                      onCheckedChange={(val) => setValue("status", val)}
                    />
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* Responsive Images */}
            <Card className="rounded-2xl border-none shadow-sm ring-1 ring-border overflow-hidden bg-card/50 backdrop-blur-sm transition-all duration-300 hover:ring-primary/20">
              <CardHeader className="pb-4">
                <CardTitle className="text-xl">Responsive Images</CardTitle>
                <CardDescription className="text-xs">
                  Upload different sizes for optimal performance and display
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                {/* Desktop Image */}
                <div className="space-y-3">
                  <div className="flex items-center justify-between">
                    <Label className="text-sm font-semibold flex items-center gap-2">
                      <Monitor className="h-4 w-4 text-primary" />
                      Desktop Image{" "}
                      <span className="text-[10px] text-muted-foreground font-normal">
                        (1920x600px)
                      </span>
                    </Label>
                    {imagePreviews.desktop && (
                      <Button
                        variant="ghost"
                        size="sm"
                        className="h-8 text-destructive hover:text-destructive hover:bg-destructive/10 rounded-lg"
                        onClick={() => removeImage("desktop")}
                      >
                        <Trash2 className="h-3.5 w-3.5 mr-1" /> Remove
                      </Button>
                    )}
                  </div>

                  {!imagePreviews.desktop ? (
                    <div
                      className={cn(
                        "border-2 border-dashed rounded-2xl flex flex-col items-center justify-center py-12 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"
                      )}
                    >
                      <Input
                        type="file"
                        id="desktop-upload"
                        className="absolute inset-0 opacity-0 cursor-pointer z-10"
                        accept="image/*"
                        onChange={(e) => handleFileChange(e, "desktop")}
                      />
                      <div className="h-14 w-14 rounded-2xl bg-primary/10 flex items-center justify-center mb-4 group-hover:scale-110 group-hover:rotate-2 transition-all">
                        <ImagePlus className="h-7 w-7 text-primary" />
                      </div>
                      <p className="text-sm font-semibold">
                        Drop desktop image here
                      </p>
                      <p className="text-xs text-muted-foreground mt-1">
                        Recommended 1920x600px | Max 5MB
                      </p>
                    </div>
                  ) : (
                    <div className="relative rounded-2xl overflow-hidden aspect-16/5 group shadow-lg ring-1 ring-border/50">
                      <img
                        src={imagePreviews.desktop}
                        className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105"
                        alt="Desktop preview"
                      />
                      <div className="absolute inset-0 bg-black/60 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center backdrop-blur-sm">
                        <Button
                          variant="secondary"
                          size="sm"
                          className="rounded-xl shadow-xl"
                          onClick={() =>
                            document
                              .getElementById("desktop-upload-alt")
                              ?.click()
                          }
                        >
                          Change Desktop Image
                        </Button>
                        <input
                          type="file"
                          id="desktop-upload-alt"
                          className="hidden"
                          accept="image/*"
                          onChange={(e) => handleFileChange(e, "desktop")}
                        />
                      </div>
                    </div>
                  )}
                  {errors.desktop_image && (
                    <p className="text-xs text-destructive mt-2 inline-flex items-center gap-1.5 font-medium">
                      <span className="h-1 w-1 rounded-full bg-destructive" />{" "}
                      {errors.desktop_image.message as string}
                    </p>
                  )}
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-6 pt-2">
                  {/* Tablet Image */}
                  <div className="space-y-3">
                    <Label className="text-sm font-semibold flex items-center gap-2">
                      <Tablet className="h-4 w-4 text-primary" />
                      Tablet Image{" "}
                      <span className="text-[10px] text-muted-foreground font-normal">
                        (1024x640px)
                      </span>
                    </Label>
                    {!imagePreviews.tablet ? (
                      <div className="border-2 border-dashed rounded-2xl flex flex-col items-center justify-center py-8 bg-muted/5 transition-all duration-200 hover:bg-muted/10 hover:border-primary/50 cursor-pointer group relative h-[140px]">
                        <Input
                          type="file"
                          id="tablet-upload"
                          className="absolute inset-0 opacity-0 cursor-pointer z-10"
                          accept="image/*"
                          onChange={(e) => handleFileChange(e, "tablet")}
                        />
                        <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 transition-colors">
                          Choose Tablet
                        </p>
                      </div>
                    ) : (
                      <div className="relative rounded-2xl overflow-hidden h-[140px] group shadow-inner 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="Tablet preview"
                        />
                        <div className="absolute top-2 right-2">
                          <Button
                            size="icon"
                            variant="destructive"
                            className="h-8 w-8 rounded-full shadow-xl"
                            onClick={() => removeImage("tablet")}
                          >
                            <Trash2 className="h-3.5 w-3.5" />
                          </Button>
                        </div>
                      </div>
                    )}
                  </div>

                  {/* Mobile Image */}
                  <div className="space-y-3">
                    <Label className="text-sm font-semibold flex items-center gap-2">
                      <Smartphone className="h-4 w-4 text-primary" />
                      Mobile Image{" "}
                      <span className="text-[10px] text-muted-foreground font-normal">
                        (768x500px)
                      </span>
                    </Label>
                    {!imagePreviews.mobile ? (
                      <div className="border-2 border-dashed rounded-2xl flex flex-col items-center justify-center py-8 bg-muted/5 transition-all duration-200 hover:bg-muted/10 hover:border-primary/50 cursor-pointer group relative h-[140px]">
                        <Input
                          type="file"
                          id="mobile-upload"
                          className="absolute inset-0 opacity-0 cursor-pointer z-10"
                          accept="image/*"
                          onChange={(e) => handleFileChange(e, "mobile")}
                        />
                        <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 transition-colors">
                          Choose Mobile
                        </p>
                      </div>
                    ) : (
                      <div className="relative rounded-2xl overflow-hidden h-[140px] group shadow-inner 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="Mobile preview"
                        />
                        <div className="absolute top-2 right-2">
                          <Button
                            size="icon"
                            variant="destructive"
                            className="h-8 w-8 rounded-full shadow-xl"
                            onClick={() => removeImage("mobile")}
                          >
                            <Trash2 className="h-3.5 w-3.5" />
                          </Button>
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* Call-to-Action Buttons */}
            <Card className="rounded-2xl border-none shadow-sm ring-1 ring-border bg-card/50 backdrop-blur-sm transition-all duration-300 hover:ring-primary/20">
              <CardHeader className="pb-4 border-b bg-muted/5">
                <CardTitle className="text-xl">
                  Call-to-Action Buttons
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-8 pt-8">
                <div className="p-6 rounded-2xl bg-primary/3 border border-primary/10 space-y-6 relative overflow-hidden group">
                  <div className="absolute top-0 right-0 h-24 w-24 bg-primary/5 rounded-full -mr-12 -mt-12 transition-transform group-hover:scale-150 duration-700" />
                  <div className="badge inline-flex bg-primary/10 text-primary text-[10px] uppercase font-black px-3 py-1 rounded-full relative z-10">
                    Primary Button
                  </div>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6 relative z-10">
                    <div className="space-y-2">
                      <Label className="text-xs font-bold text-muted-foreground/80 uppercase tracking-wider">
                        Button Text
                      </Label>
                      <Input
                        placeholder="e.g., Get Started"
                        {...register("primary_button_text")}
                        className="rounded-xl h-11 bg-background"
                      />
                    </div>
                    <div className="space-y-2">
                      <Label className="text-xs font-bold text-muted-foreground/80 uppercase tracking-wider">
                        Button URL
                      </Label>
                      <Input
                        placeholder="https://example.com"
                        {...register("primary_button_url")}
                        className="rounded-xl h-11 bg-background"
                      />
                    </div>
                  </div>
                </div>

                <div className="p-6 rounded-2xl bg-muted/20 border border-muted/50 space-y-6 relative overflow-hidden group">
                  <div className="absolute top-0 right-0 h-24 w-24 bg-muted/30 rounded-full -mr-12 -mt-12 transition-transform group-hover:scale-150 duration-700" />
                  <div className="badge inline-flex bg-muted text-muted-foreground text-[10px] uppercase font-black px-3 py-1 rounded-full relative z-10">
                    Secondary Button
                  </div>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6 relative z-10">
                    <div className="space-y-2">
                      <Label className="text-xs font-bold text-muted-foreground/80 uppercase tracking-wider">
                        Button Text
                      </Label>
                      <Input
                        placeholder="e.g., Learn More"
                        {...register("secondary_button_text")}
                        className="rounded-xl h-11 bg-background"
                      />
                    </div>
                    <div className="space-y-2">
                      <Label className="text-xs font-bold text-muted-foreground/80 uppercase tracking-wider">
                        Button URL
                      </Label>
                      <Input
                        placeholder="https://example.com"
                        {...register("secondary_button_url")}
                        className="rounded-xl h-11 bg-background"
                      />
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
            {/* Hidden Submit Button */}
            <button type="submit" ref={formRef} className="hidden" />
          </form>

          {/* Footer Actions matched to Reference */}
          <div className="flex items-center justify-end gap-3 px-5 py-4 border-t border-border bg-muted/20">
            <Button
              variant="outline"
              className="rounded-xl"
              onClick={() => router.back()}
            >
              Cancel
            </Button>
            <Button
              className="rounded-xl shadow-lg shadow-primary/25"
              onClick={() => formRef.current?.click()}
              disabled={isSubmitting}
            >
              {isSubmitting ? (
                <Loader2 className="h-4 w-4 mr-2 animate-spin" />
              ) : (
                <Save className="h-4 w-4 mr-2" />
              )}
              Save Banner
            </Button>
          </div>
        </div>

        {/* Right Column: Live Previews */}
        {showPreview && (
          <div className="hidden lg:flex flex-col w-[40%] xl:w-[45%] overflow-y-auto">
            {/* Detail Header from Reference */}
            <div className="flex items-center justify-between px-5 py-3 border-b border-border bg-muted/20">
              <div className="flex items-center gap-2">
                <Eye className="h-4 w-4 text-primary" />
                <h3 className="text-sm font-semibold">Live Preview</h3>
              </div>
              <div className="flex items-center gap-1">
                <Button
                  variant="ghost"
                  size="sm"
                  className="h-7 w-7 p-0 rounded-full hover:bg-muted"
                  title="Fullscreen"
                >
                  <Maximize2 className="h-3.5 w-3.5" />
                </Button>
                <Button
                  variant="ghost"
                  size="sm"
                  className="h-7 w-7 p-0 rounded-full hover:bg-destructive/10 hover:text-destructive"
                  onClick={() => setShowPreview(false)}
                  title="Close Preview"
                >
                  <X className="h-4 w-4" />
                </Button>
              </div>
            </div>

            <div className="p-6">
              <BannerPreview
                data={{
                  ...watchedFields,
                  desktop_image: imagePreviews.desktop,
                  tablet_image: imagePreviews.tablet,
                  mobile_image: imagePreviews.mobile,
                }}
              />
            </div>
          </div>
        )}
      </div>
    </section>
  );
}
