"use client";

import { useRef, useState, type ChangeEvent } from "react";
import { useTranslations } from "next-intl";
import {
  ArrowRight,
  Circle,
  Clapperboard,
  Image as ImageIcon,
  Minus,
  Square,
  Type,
} from "lucide-react";

import { ToolbarIconButton } from "@/components/studio/ToolbarIconButton";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import type { ShapeKind } from "@/lib/studio-layer-props";
import type { AddLayerInput } from "@/lib/studio-types";
import { useStudioStore } from "@/lib/studio-store";
import { ALLOW_ADD_LAYERS } from "@/lib/studio-config";

const SHAPE_OPTIONS: {
  kind: ShapeKind;
  labelKey: string;
  icon: typeof Square;
  config: AddLayerInput;
}[] = [
  {
    kind: "rect",
    labelKey: "shapeRectangle",
    icon: Square,
    config: {
      type: "shape",
      x: 100,
      y: 100,
      width: 320,
      height: 180,
      props: { shape: "rect", fill: "#2563EB", stroke: "#1E3A8A", strokeWidth: 0 },
    },
  },
  {
    kind: "circle",
    labelKey: "shapeCircle",
    icon: Circle,
    config: {
      type: "shape",
      x: 100,
      y: 100,
      width: 180,
      height: 180,
      props: { shape: "circle", fill: "#7C3AED" },
    },
  },
  {
    kind: "line",
    labelKey: "shapeLine",
    icon: Minus,
    config: {
      type: "shape",
      x: 100,
      y: 200,
      width: 240,
      height: 8,
      props: { shape: "line", stroke: "#FFFFFF", strokeWidth: 4, fill: "#FFFFFF" },
    },
  },
  {
    kind: "arrow",
    labelKey: "shapeArrow",
    icon: ArrowRight,
    config: {
      type: "shape",
      x: 100,
      y: 200,
      width: 200,
      height: 40,
      props: {
        shape: "arrow",
        stroke: "#FFFFFF",
        strokeWidth: 4,
        fill: "#FFFFFF",
      },
    },
  },
];

export function StudioToolbar() {
  const t = useTranslations("auto.componentsStudioStudioToolbar");
  const addLayer = useStudioStore((state) => state.addLayer);
  const imageInputRef = useRef<HTMLInputElement>(null);
  const videoInputRef = useRef<HTMLInputElement>(null);
  const [shapeOpen, setShapeOpen] = useState(false);

  // Template projects have a predefined structure — adding new layers is disabled.
  if (!ALLOW_ADD_LAYERS) return null;

  const handleAddText = () => {
    addLayer({
      type: "text",
      x: 100,
      y: 100,
      width: 300,
      height: 60,
      props: {
        text: t("defaultText"),
        fontSize: 48,
        fill: "#ffffff",
        fontFamily: "Inter, sans-serif",
      },
    });
  };

  const handleImageFile = (event: ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = () => {
      if (typeof reader.result === "string") {
        addLayer({
          type: "image",
          x: 100,
          y: 100,
          width: 400,
          height: 300,
          props: { src: reader.result },
        });
      }
    };
    reader.readAsDataURL(file);
    event.target.value = "";
  };

  const handleVideoFile = (event: ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    const objectUrl = URL.createObjectURL(file);
    addLayer({
      type: "video",
      x: 100,
      y: 100,
      width: 480,
      height: 270,
      props: { src: objectUrl, fileName: file.name },
    });
    event.target.value = "";
  };

  return (
    <div className="flex items-center gap-1">
      <input
        ref={imageInputRef}
        type="file"
        accept="image/*"
        className="hidden"
        onChange={handleImageFile}
      />
      <input
        ref={videoInputRef}
        type="file"
        accept="video/*"
        className="hidden"
        onChange={handleVideoFile}
      />

      <ToolbarIconButton label={t("addText")} onClick={handleAddText}>
        <Type className="h-4 w-4" aria-hidden />
      </ToolbarIconButton>

      <ToolbarIconButton
        label={t("addImage")}
        onClick={() => imageInputRef.current?.click()}
      >
        <ImageIcon className="h-4 w-4" aria-hidden />
      </ToolbarIconButton>

      <ToolbarIconButton
        label={t("addVideoClip")}
        onClick={() => videoInputRef.current?.click()}
      >
        <Clapperboard className="h-4 w-4" aria-hidden />
      </ToolbarIconButton>

      <Popover open={shapeOpen} onOpenChange={setShapeOpen}>
        <PopoverTrigger asChild>
          <div className="group relative">
            <button
              type="button"
              aria-label={t("addShape")}
              className="flex h-9 w-9 items-center justify-center rounded-lg border border-gray-200 bg-white text-gray-500 transition-colors hover:border-gray-300 hover:bg-gray-100 hover:text-gray-900 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
            >
              <Square className="h-4 w-4" aria-hidden />
            </button>
            <span
              role="tooltip"
              className="pointer-events-none absolute left-1/2 top-full z-50 mt-1.5 -translate-x-1/2 whitespace-nowrap rounded-md bg-gray-900 px-2 py-1 text-[10px] font-medium text-white opacity-0 shadow-lg transition-opacity group-hover:opacity-100 group-focus-within:opacity-100"
            >
              {t("addShape")}
            </span>
          </div>
        </PopoverTrigger>
        <PopoverContent align="center" className="w-40">
          {SHAPE_OPTIONS.map(({ kind, labelKey, icon: Icon, config }) => (
            <button
              key={kind}
              type="button"
              onClick={() => {
                addLayer(config);
                setShapeOpen(false);
              }}
              className="flex w-full items-center gap-2 rounded-md px-2 py-2 text-left text-sm text-gray-700 hover:bg-gray-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
            >
              <Icon className="h-4 w-4 shrink-0" aria-hidden />
              {t(labelKey)}
            </button>
          ))}
        </PopoverContent>
      </Popover>
    </div>
  );
}
