"use client";

import { useRef, useState } from "react";
import { ImagePlus } from "lucide-react";
import { useTranslations } from "next-intl";
import {
  CategoryPresetPicker,
  type CategoryIconSelection,
} from "@/components/menu/category-preset-picker";
import { CategoryEmojiPicker } from "@/components/menu/category-emoji-picker";
import { CategoryPresetIcon } from "@/components/menu/category-preset-icon";
import { CategoryVisual } from "@/components/menu/category-visual";
import { DEFAULT_CATEGORY_ICON_STYLE } from "@/lib/category-icon-presets";
import { apiUpload, resolveMediaUrl } from "@/lib/api/client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { LabeledField } from "@/components/ui/labeled-field";
import { cn } from "@/lib/utils";

type CategoryMediaFieldsProps = {
  cafeId: string;
  icon: string;
  iconPresetId: string | null;
  iconStyle: string | null;
  imageUrl: string;
  onIconChange: (value: string) => void;
  onPresetChange: (value: CategoryIconSelection) => void;
  onImageChange: (url: string | null) => void;
  className?: string;
};

type MediaTab = "preset" | "emoji" | "image";

export function CategoryMediaFields({
  cafeId,
  icon,
  iconPresetId,
  iconStyle,
  imageUrl,
  onIconChange,
  onPresetChange,
  onImageChange,
  className,
}: CategoryMediaFieldsProps) {
  const t = useTranslations("menuAdmin");
  const tMedia = useTranslations("media");
  const imageRef = useRef<HTMLInputElement>(null);
  const imgSrc = resolveMediaUrl(imageUrl);
  const [tab, setTab] = useState<MediaTab>(
    imageUrl ? "image" : iconPresetId ? "preset" : "preset"
  );

  const uploadImage = async (file: File) => {
    const data = await apiUpload<{ url: string }>(
      `/api/cafes/${cafeId}/media/menu-image`,
      file
    );
    onImageChange(data.url);
    onPresetChange({ iconPresetId: null, iconStyle: null });
    onIconChange("");
    setTab("image");
  };

  const tabs: { id: MediaTab; label: string }[] = [
    { id: "preset", label: t("iconTabPreset") },
    { id: "emoji", label: t("iconTabEmoji") },
    { id: "image", label: t("iconTabImage") },
  ];

  return (
    <div className={cn("space-y-3", className)}>
      <div className="flex flex-wrap gap-1.5">
        {tabs.map(({ id, label }) => (
          <button
            key={id}
            type="button"
            onClick={() => setTab(id)}
            className={cn(
              "rounded-md border px-2.5 py-1 text-xs font-medium transition-colors",
              tab === id
                ? "border-[#0F6E56] bg-[#E1F5EE] text-[#0F6E56]"
                : "border-border/80 text-muted-foreground hover:border-[#0F6E56]/40"
            )}
          >
            {label}
          </button>
        ))}
      </div>

      {tab === "preset" ? (
        <CategoryPresetPicker
          value={{
            iconPresetId,
            iconStyle: (iconStyle as CategoryIconSelection["iconStyle"]) ?? DEFAULT_CATEGORY_ICON_STYLE,
          }}
          onChange={(next) => {
            onPresetChange(next);
            if (next.iconPresetId) onIconChange("");
            onImageChange(null);
          }}
        />
      ) : null}

      {tab === "emoji" ? (
        <div className="space-y-3 rounded-lg border border-border/80 bg-muted/20 p-3">
          {icon.trim() ? (
            <div className="flex items-center gap-2 text-xs text-muted-foreground">
              <span>{t("iconPreview")}</span>
              <CategoryVisual icon={icon} size="md" />
              <button
                type="button"
                className="text-[#0F6E56] underline-offset-2 hover:underline"
                onClick={() => onIconChange("")}
              >
                {t("clearIconEmoji")}
              </button>
            </div>
          ) : null}
          <CategoryEmojiPicker
            value={icon}
            onChange={(emoji) => {
              onIconChange(emoji);
              onPresetChange({ iconPresetId: null, iconStyle: null });
              onImageChange(null);
            }}
          />
          <LabeledField label={t("categoryIconCustom")} htmlFor="cat-icon" className="max-w-[10rem]">
            <Input
              id="cat-icon"
              value={icon}
              onChange={(e) => {
                onIconChange(e.target.value);
                if (e.target.value.trim()) {
                  onPresetChange({ iconPresetId: null, iconStyle: null });
                  onImageChange(null);
                }
              }}
              placeholder="☕"
              className="text-center text-lg"
              maxLength={16}
            />
          </LabeledField>
        </div>
      ) : null}

      {tab === "image" ? (
        <div className="space-y-2">
          <input
            ref={imageRef}
            type="file"
            accept="image/jpeg,image/png,image/webp"
            className="hidden"
            onChange={(e) => {
              const f = e.target.files?.[0];
              if (f) void uploadImage(f);
            }}
          />
          <div className="flex flex-wrap items-center gap-2">
            <Button type="button" size="sm" variant="outline" onClick={() => imageRef.current?.click()}>
              <ImagePlus className="me-1 h-3.5 w-3.5" />
              {t("categoryImage")}
            </Button>
            {imageUrl ? (
              <Button type="button" size="sm" variant="ghost" onClick={() => onImageChange(null)}>
                {tMedia("removeImage")}
              </Button>
            ) : null}
            {iconPresetId ? (
              <CategoryPresetIcon presetId={iconPresetId} style={iconStyle} size="sm" />
            ) : null}
          </div>
          {imgSrc ? (
            // eslint-disable-next-line @next/next/no-img-element
            <img src={imgSrc} alt="" className="h-16 w-16 rounded-lg border object-cover" />
          ) : null}
        </div>
      ) : null}
    </div>
  );
}
