"use client";

import { ImagesIcon, RefreshCwIcon, Trash2Icon } from "lucide-react";
import { useState } from "react";

import { Button } from "@/components/ui/button";
import { Field, FieldDescription, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { Progress } from "@/components/ui/progress";
import type { ImageValue, MediaItem } from "@/features/media/types";
import { useImageUpload } from "@/features/media/use-image-upload";
import { cn } from "@/lib/utils";

import { Dropzone } from "./dropzone";
import { MediaPickerDialog } from "./media-picker-dialog";

/**
 * A single-image field: upload, drag and drop, pick from the library,
 * replace and remove. Optionally edits alt text and title alongside.
 */
export function ImageField({
  value,
  onChange,
  recommended,
  withMeta = false,
  aspect = "video",
  className,
  idPrefix,
}: {
  value: ImageValue | null;
  onChange: (value: ImageValue | null) => void;
  recommended?: { width: number; height: number };
  /** Show alt text and title inputs. */
  withMeta?: boolean;
  /** Preview shape. "card" is the website's CTA card image (360 × 260). */
  aspect?: "video" | "square" | "og" | "card";
  className?: string;
  idPrefix: string;
}) {
  const [pickerOpen, setPickerOpen] = useState(false);
  const { upload, tasks, uploading, maxUploadMb } = useImageUpload();
  const current = tasks.findLast((task) => task.status === "uploading");

  const fromMedia = (media: MediaItem): ImageValue => ({
    url: media.url,
    alt: media.altText || value?.alt || "",
    title: media.title ?? value?.title ?? "",
  });

  const handleFiles = async (files: File[]) => {
    const [media] = await upload(files);
    if (media) onChange(fromMedia(media));
  };

  const aspectClass =
    aspect === "square"
      ? "aspect-square"
      : aspect === "og"
        ? "aspect-[1.91/1]"
        : aspect === "card"
          ? "aspect-[18/13]"
          : "aspect-video";

  const hint = recommended
    ? `Recommended ${recommended.width} × ${recommended.height}px. JPG, PNG, WebP or AVIF up to ${maxUploadMb} MB.`
    : `JPG, PNG, WebP or AVIF up to ${maxUploadMb} MB.`;

  return (
    <div className={cn("space-y-3", className)}>
      {value ? (
        <Dropzone
          onFiles={handleFiles}
          disabled={uploading}
          className={cn(
            "group overflow-hidden border-solid bg-muted p-0",
            aspectClass,
          )}
        >
          {/* eslint-disable-next-line @next/next/no-img-element -- preview of an arbitrary upload */}
          <img
            src={value.url}
            alt={value.alt}
            className="absolute inset-0 size-full object-cover"
          />
          <div
            className="absolute inset-x-0 bottom-0 flex justify-end gap-1.5 bg-gradient-to-t from-black/50 to-transparent p-2 opacity-100 transition-opacity sm:opacity-0 sm:group-focus-within:opacity-100 sm:group-hover:opacity-100"
            onClick={(event) => event.stopPropagation()}
          >
            <Button
              type="button"
              size="sm"
              variant="secondary"
              onClick={() => setPickerOpen(true)}
            >
              <RefreshCwIcon />
              Replace
            </Button>
            <Button
              type="button"
              size="icon-sm"
              variant="secondary"
              aria-label="Remove image"
              onClick={() => onChange(null)}
            >
              <Trash2Icon />
            </Button>
          </div>
          {current && (
            <div className="absolute inset-x-3 top-3 rounded-md bg-background/90 p-2 text-xs shadow-soft">
              Uploading… {current.progress}%
              <Progress value={current.progress} className="mt-1 h-1" />
            </div>
          )}
        </Dropzone>
      ) : (
        <div className="space-y-2">
          <Dropzone
            onFiles={handleFiles}
            disabled={uploading}
            className={aspectClass}
          >
            {current ? (
              <div className="w-full max-w-48 space-y-2 text-sm">
                <p className="font-medium">Uploading… {current.progress}%</p>
                <Progress value={current.progress} className="h-1.5" />
              </div>
            ) : undefined}
          </Dropzone>
          <Button
            type="button"
            variant="outline"
            size="sm"
            className="w-full"
            onClick={() => setPickerOpen(true)}
            disabled={uploading}
          >
            <ImagesIcon />
            Choose from library
          </Button>
        </div>
      )}
      <p className="text-xs text-muted-foreground">{hint}</p>

      {value && withMeta && (
        <div className="space-y-3">
          <Field>
            <FieldLabel htmlFor={`${idPrefix}-alt`}>Alt text</FieldLabel>
            <Input
              id={`${idPrefix}-alt`}
              value={value.alt}
              maxLength={300}
              placeholder="Describe the image for screen readers"
              onChange={(event) =>
                onChange({ ...value, alt: event.target.value })
              }
            />
            {!value.alt.trim() && (
              <FieldDescription className="text-warning">
                Add alt text for accessibility and SEO.
              </FieldDescription>
            )}
          </Field>
          <Field>
            <FieldLabel htmlFor={`${idPrefix}-title`}>Title</FieldLabel>
            <Input
              id={`${idPrefix}-title`}
              value={value.title}
              maxLength={200}
              placeholder="Optional"
              onChange={(event) =>
                onChange({ ...value, title: event.target.value })
              }
            />
          </Field>
        </div>
      )}

      <MediaPickerDialog
        open={pickerOpen}
        onOpenChange={setPickerOpen}
        onSelect={(media) => onChange(fromMedia(media))}
      />
    </div>
  );
}
