"use client";

import { useId, useRef, useState } from "react";
import { ImagePlus, Loader2, Lock, X } from "lucide-react";
import { cn } from "@/shared/lib/utils";
import { useT } from "@/shared/i18n/client";
import { useRepositories } from "@/di/repository-provider";
import { ANNOUNCEMENT_BACKGROUNDS, ANNOUNCEMENT_ICONS, ANNOUNCEMENT_LIMITS, FORMAT_FIELDS } from "@/shared/constants/announcements";
import { slugify } from "@/shared/lib/announcements";
import { Input } from "@/presentation/components/ui/input";
import { AnnouncementIcon } from "@/presentation/components/announcements/announcement-badges";
import {
  FieldErrors,
  FieldLabel,
  Help,
  LocalizedInput,
  LocalizedRichText,
} from "@/presentation/components/announcements/form-controls";
import { EditorSection, type SectionProps } from "@/presentation/components/announcements/editor-sections/section";
import type { AnnouncementFieldErrors, LocalizedText } from "@/domain/entities/announcement";

export function ContentSection({ input, update, errors, locked, disabled }: SectionProps) {
  const t = useT();
  const e = t.announcements.editor;
  const spec = FORMAT_FIELDS[input.format];
  const keyId = useId();
  const categoryId = useId();

  // The key follows the FR title until someone types their own (and never after the first publish).
  const onTitle = (title: LocalizedText) => {
    const follows = !locked && (!input.key || input.key === slugify(input.title.fr));
    update(follows ? { title, key: slugify(title.fr) } : { title });
  };

  return (
    <EditorSection id="section-content" index={2} title={e.sections.content.title} help={e.sections.content.help}>
      <LocalizedInput
        label={e.title}
        path="title"
        value={input.title}
        onChange={onTitle}
        errors={errors}
        max={ANNOUNCEMENT_LIMITS.title}
        required
        disabled={disabled}
      />

      <div className="grid gap-4 md:grid-cols-2">
        <div className="space-y-1.5">
          <FieldLabel htmlFor={keyId} required hint={locked ? <Lock className="h-3 w-3" /> : undefined}>{e.key}</FieldLabel>
          <Input
            id={keyId}
            value={input.key}
            disabled={disabled || locked}
            onChange={(ev) => update({ key: ev.target.value.toLowerCase().replace(/[^a-z0-9-]/g, "-").slice(0, 60) })}
            className="font-mono text-sm"
            aria-invalid={!!errors.key}
          />
          <FieldErrors errors={errors} path="key" />
          <Help>{locked ? e.keyLocked : e.keyHelp}</Help>
        </div>
        <div className="space-y-1.5">
          <FieldLabel htmlFor={categoryId}>{e.category}</FieldLabel>
          <Input
            id={categoryId}
            value={input.category ?? ""}
            disabled={disabled}
            maxLength={40}
            placeholder={e.categoryPlaceholder}
            onChange={(ev) => update({ category: ev.target.value || null })}
          />
        </div>
      </div>

      {spec.bodyMax > 0 && (
        <LocalizedRichText
          label={e.body}
          path="body"
          value={input.body}
          onChange={(body) => update({ body })}
          errors={errors}
          max={spec.bodyMax}
          required
          disabled={disabled}
        />
      )}

      {spec.badgeText && (
        // On a badge, its text; on a card (pop-up, banner, modal), the small chip at its top.
        <LocalizedInput
          label={input.format === "badge" ? e.badgeText : e.chipText}
          path="badge_text"
          value={input.badge_text}
          onChange={(badge_text) => update({ badge_text })}
          errors={errors}
          max={ANNOUNCEMENT_LIMITS.badgeText}
          required={input.format === "badge"}
          help={input.format === "badge" ? undefined : e.chipTextHelp}
          disabled={disabled}
        />
      )}

      <IconPicker value={input.icon} onChange={(icon) => update({ icon })} disabled={disabled} />

      {spec.background && (
        <BackgroundPicker value={input.background_color} onChange={(background_color) => update({ background_color })} errors={errors} disabled={disabled} />
      )}

      {spec.image && (
        <MediaField
          path="media"
          url={input.media_url}
          alt={input.media_alt}
          onChange={(media_url, media_alt) => update({ media_url, media_alt })}
          errors={errors}
          disabled={disabled}
        />
      )}

      {spec.cta && (
        <CtaFields
          path="cta"
          label={input.cta_label}
          ctaPath={input.cta_path}
          onChange={(cta_label, cta_path) => update({ cta_label, cta_path })}
          errors={errors}
          disabled={disabled}
        />
      )}
    </EditorSection>
  );
}

export function IconPicker({ value, onChange, disabled }: { value: string | null; onChange: (icon: string | null) => void; disabled?: boolean }) {
  const t = useT();
  const e = t.announcements.editor;
  return (
    <div className="space-y-1.5">
      <FieldLabel>{e.icon}</FieldLabel>
      <div className="flex flex-wrap gap-1.5" role="radiogroup" aria-label={e.icon}>
        <button
          type="button"
          role="radio"
          aria-checked={!value}
          disabled={disabled}
          onClick={() => onChange(null)}
          className={cn("h-9 rounded-md border px-2.5 text-xs", !value ? "border-blue-600 bg-blue-50 text-blue-700" : "text-muted-foreground hover:bg-muted")}
        >
          {e.noIcon}
        </button>
        {ANNOUNCEMENT_ICONS.map((name) => (
          <button
            key={name}
            type="button"
            role="radio"
            aria-checked={value === name}
            aria-label={name}
            title={name}
            disabled={disabled}
            onClick={() => onChange(name)}
            className={cn(
              "flex h-9 w-9 items-center justify-center rounded-md border",
              value === name ? "border-blue-600 bg-blue-50 text-blue-700" : "text-muted-foreground hover:bg-muted",
            )}
          >
            <AnnouncementIcon name={name} className="h-4 w-4" />
          </button>
        ))}
      </div>
    </div>
  );
}

export function BackgroundPicker({
  value,
  onChange,
  errors,
  disabled,
}: {
  value: string | null;
  onChange: (color: string | null) => void;
  errors: AnnouncementFieldErrors;
  disabled?: boolean;
}) {
  const t = useT();
  const e = t.announcements.editor;
  const custom = !!value && !(ANNOUNCEMENT_BACKGROUNDS as readonly string[]).includes(value.toUpperCase());
  return (
    <div className="space-y-1.5">
      <FieldLabel>{e.backgroundColor}</FieldLabel>
      <div className="flex flex-wrap items-center gap-1.5" role="radiogroup" aria-label={e.backgroundColor}>
        <button
          type="button"
          role="radio"
          aria-checked={!value}
          disabled={disabled}
          onClick={() => onChange(null)}
          className={cn("h-9 rounded-md border px-2.5 text-xs", !value ? "border-blue-600 bg-blue-50 text-blue-700" : "text-muted-foreground hover:bg-muted")}
        >
          {e.backgroundDefault}
        </button>
        {ANNOUNCEMENT_BACKGROUNDS.map((color) => (
          <button
            key={color}
            type="button"
            role="radio"
            aria-checked={value?.toUpperCase() === color}
            aria-label={color}
            title={color}
            disabled={disabled}
            onClick={() => onChange(color)}
            className={cn(
              "h-9 w-9 rounded-md border",
              value?.toUpperCase() === color ? "ring-2 ring-blue-600 ring-offset-1" : "hover:opacity-80",
            )}
            style={{ backgroundColor: color }}
          />
        ))}
        <label
          className={cn(
            "inline-flex h-9 cursor-pointer items-center gap-1.5 rounded-md border px-2.5 text-xs",
            custom ? "border-blue-600 bg-blue-50 text-blue-700" : "text-muted-foreground hover:bg-muted",
          )}
        >
          <input
            type="color"
            value={value ?? "#FEF3C7"}
            disabled={disabled}
            onChange={(ev) => onChange(ev.target.value.toUpperCase())}
            className="h-5 w-5 cursor-pointer border-0 bg-transparent p-0"
          />
          {custom ? value : e.backgroundCustom}
        </label>
      </div>
      <FieldErrors errors={errors} path="background_color" />
      <Help>{e.backgroundHelp}</Help>
    </div>
  );
}

export function MediaField({
  path,
  url,
  alt,
  onChange,
  errors,
  disabled,
}: {
  path: string;
  url: string | null;
  alt: LocalizedText;
  onChange: (url: string | null, alt: LocalizedText) => void;
  errors: AnnouncementFieldErrors;
  disabled?: boolean;
}) {
  const t = useT();
  const e = t.announcements.editor;
  const { announcementRepository } = useRepositories();
  const fileRef = useRef<HTMLInputElement>(null);
  const [uploading, setUploading] = useState(false);
  const [problem, setProblem] = useState<string | null>(null);

  const pick = async (file: File | undefined) => {
    if (!file) return;
    if (!(ANNOUNCEMENT_LIMITS.imageTypes as readonly string[]).includes(file.type)) return setProblem(e.imageBadType);
    if (file.size > ANNOUNCEMENT_LIMITS.imageMaxBytes) return setProblem(e.imageTooBig);
    setProblem(null);
    setUploading(true);
    try {
      const { url: uploaded } = await announcementRepository.uploadMedia(file);
      onChange(uploaded, alt);
    } catch (err) {
      setProblem((err as Error).message);
    } finally {
      setUploading(false);
      if (fileRef.current) fileRef.current.value = "";
    }
  };

  return (
    <div className="space-y-3">
      <div className="space-y-1.5">
        <FieldLabel>{e.image}</FieldLabel>
        <div className="flex flex-wrap items-center gap-3">
          {url ? (
            <div className="relative">
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img src={url} alt={alt.fr} className="h-20 w-36 rounded-md border object-cover" />
              <button
                type="button"
                onClick={() => onChange(null, { fr: "", en: "" })}
                disabled={disabled}
                className="absolute -right-2 -top-2 rounded-full border bg-background p-0.5 shadow hover:text-destructive"
                aria-label={e.imageRemove}
              >
                <X className="h-3.5 w-3.5" />
              </button>
            </div>
          ) : null}
          <input
            ref={fileRef}
            type="file"
            accept={ANNOUNCEMENT_LIMITS.imageTypes.join(",")}
            className="sr-only"
            onChange={(ev) => void pick(ev.target.files?.[0])}
            tabIndex={-1}
          />
          <button
            type="button"
            disabled={disabled || uploading}
            onClick={() => fileRef.current?.click()}
            className="inline-flex h-9 items-center gap-1.5 rounded-md border px-3 text-sm hover:bg-muted disabled:opacity-50"
          >
            {uploading ? <Loader2 className="h-4 w-4 animate-spin" /> : <ImagePlus className="h-4 w-4" />}
            {e.imageUpload}
          </button>
        </div>
        {problem && <p className="text-xs font-medium text-destructive">{problem}</p>}
        <Help>{e.imageHelp}</Help>
      </div>
      {url && (
        <LocalizedInput
          label={e.imageAlt}
          path={`${path}_alt`}
          value={alt}
          onChange={(next) => onChange(url, next)}
          errors={errors}
          max={120}
          required
          help={e.imageAltHelp}
          disabled={disabled}
        />
      )}
    </div>
  );
}

export function CtaFields({
  path,
  label,
  ctaPath,
  onChange,
  errors,
  disabled,
}: {
  path: string;
  label: LocalizedText;
  ctaPath: string | null;
  onChange: (label: LocalizedText, path: string | null) => void;
  errors: AnnouncementFieldErrors;
  disabled?: boolean;
}) {
  const t = useT();
  const e = t.announcements.editor;
  const id = useId();
  return (
    <div className="space-y-3 rounded-lg border border-dashed p-3">
      <p className="text-sm font-medium">{e.cta}</p>
      <LocalizedInput
        label={e.ctaLabel}
        path={`${path}_label`}
        value={label}
        onChange={(next) => onChange(next, ctaPath)}
        errors={errors}
        max={ANNOUNCEMENT_LIMITS.ctaLabel}
        disabled={disabled}
      />
      <div className="space-y-1.5">
        <FieldLabel htmlFor={id}>{e.ctaPath}</FieldLabel>
        <Input
          id={id}
          value={ctaPath ?? ""}
          disabled={disabled}
          placeholder="/fleet/…"
          className="font-mono text-sm"
          onChange={(ev) => onChange(label, ev.target.value.trim() || null)}
          aria-invalid={!!errors[`${path}_path`]}
        />
        <FieldErrors errors={errors} path={`${path}_path`} />
        <Help>{e.ctaPathHelp}</Help>
      </div>
    </div>
  );
}
