"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import { Cable, ImageUp, RotateCcw, Trash2 } from "lucide-react";
import { useT } from "@/shared/i18n/client";
import { Button } from "@/presentation/components/ui/button";
import { checkLogoFile, LOGO_ACCEPT } from "@/shared/lib/integration-logo";

/** What the admin chose in the form, sent when the connector is saved. */
export type IntegrationLogoChange = { kind: "file"; file: File } | { kind: "remove" } | null;

interface Props {
  /** The logo saved now, or null. */
  currentSrc: string | null;
  alt: string;
  change: IntegrationLogoChange;
  onChange: (change: IntegrationLogoChange) => void;
  disabled?: boolean;
}

/**
 * The logo field of a connector's sheet in edit mode (SCRUM-601): choose or drop a PNG, SVG or JPEG of 5 MB at most,
 * see it at once, or mark the logo for removal. Nothing is sent before « Enregistrer les modifications ».
 */
export function IntegrationLogoField({ currentSrc, alt, change, onChange, disabled }: Props) {
  const t = useT();
  const l = t.pages.integrations.detail.logo;
  const input = useRef<HTMLInputElement>(null);
  const [problem, setProblem] = useState<string | null>(null);
  const [dragging, setDragging] = useState(false);
  // The preview of a chosen file lives as long as the choice.
  const preview = useMemo(() => (change?.kind === "file" ? URL.createObjectURL(change.file) : null), [change]);
  useEffect(() => () => {
    if (preview) URL.revokeObjectURL(preview);
  }, [preview]);

  const pick = (file: File | undefined) => {
    if (!file) return;
    const issue = checkLogoFile(file);
    if (issue) {
      setProblem(l.errors[issue]);
      return;
    }
    setProblem(null);
    onChange({ kind: "file", file });
  };

  const shown = change?.kind === "remove" ? null : preview ?? currentSrc;
  const hasLogo = Boolean(shown);

  return (
    <div className="space-y-1.5" data-testid="integration-logo-field">
      <label className="text-xs font-semibold text-muted-foreground">{l.title}</label>
      <div
        className={`flex items-center gap-4 rounded-xl border border-dashed p-3 transition-colors ${
          dragging ? "border-primary bg-primary/5" : "border-border bg-background"
        }`}
        onDragOver={(e) => {
          e.preventDefault();
          if (!disabled) setDragging(true);
        }}
        onDragLeave={() => setDragging(false)}
        onDrop={(e) => {
          e.preventDefault();
          setDragging(false);
          if (!disabled) pick(e.dataTransfer.files?.[0]);
        }}
      >
        <div className="w-16 h-16 rounded-lg bg-muted/40 flex items-center justify-center border border-border shrink-0 overflow-hidden">
          {shown ? (
            <img src={shown} alt={alt} className="w-full h-full object-contain p-1.5" />
          ) : (
            <Cable className="w-6 h-6 text-muted-foreground" />
          )}
        </div>
        <div className="min-w-0 flex-1 space-y-2">
          <p className="text-xs text-muted-foreground">
            {change?.kind === "file"
              ? l.pending
              : change?.kind === "remove"
                ? l.pendingRemoval
                : hasLogo
                  ? l.dropHint
                  : l.none}
          </p>
          <div className="flex flex-wrap gap-2">
            <Button
              type="button"
              variant="outline"
              size="sm"
              className="h-8 text-xs"
              disabled={disabled}
              onClick={() => input.current?.click()}
            >
              <ImageUp className="w-3.5 h-3.5 mr-1.5" />
              {hasLogo ? l.replace : l.choose}
            </Button>
            {change ? (
              <Button
                type="button"
                variant="ghost"
                size="sm"
                className="h-8 text-xs"
                disabled={disabled}
                onClick={() => {
                  setProblem(null);
                  onChange(null);
                }}
              >
                <RotateCcw className="w-3.5 h-3.5 mr-1.5" />
                {l.undo}
              </Button>
            ) : currentSrc ? (
              <Button
                type="button"
                variant="ghost"
                size="sm"
                className="h-8 text-xs text-destructive hover:text-destructive"
                disabled={disabled}
                onClick={() => {
                  setProblem(null);
                  onChange({ kind: "remove" });
                }}
              >
                <Trash2 className="w-3.5 h-3.5 mr-1.5" />
                {l.remove}
              </Button>
            ) : null}
          </div>
          <p className="text-[11px] text-muted-foreground">{l.formats}</p>
        </div>
        <input
          ref={input}
          type="file"
          accept={LOGO_ACCEPT}
          className="hidden"
          aria-label={l.choose}
          onChange={(e) => {
            pick(e.target.files?.[0]);
            // The same file can be chosen again after an undo.
            e.target.value = "";
          }}
        />
      </div>
      {problem ? (
        <p className="text-xs font-medium text-destructive" role="alert">
          {problem}
        </p>
      ) : null}
    </div>
  );
}
