"use client";

import { useState, type ComponentProps } from "react";
import dynamic from "next/dynamic";
import { SlidersHorizontal } from "lucide-react";
import { useTranslations } from "next-intl";

import { AiRemoveBgModal } from "@/components/image-editor/AiRemoveBgModal";
import { ImageCropControls } from "@/components/image-editor/ImageCropControls";
import { ImageEditorRightPanel } from "@/components/image-editor/ImageEditorRightPanel";
import {
  IMAGE_SHAPES,
  IMAGE_TOOLS,
} from "@/components/image-editor/ImageEditorToolbar";
import { ImageEditorTopBar } from "@/components/image-editor/ImageEditorTopBar";
import { BottomSheet } from "@/components/studio/mobile/BottomSheet";
import { Toaster } from "@/components/ui/toaster";
import { useImageEditorStore } from "@/lib/image-editor-store";
import { cn } from "@/lib/utils";

const ImageEditorCanvas = dynamic(
  () =>
    import("@/components/image-editor/canvas/ImageEditorCanvas").then(
      (mod) => mod.ImageEditorCanvas,
    ),
  { ssr: false, loading: () => <div className="h-full w-full bg-gray-950" /> },
);

type TopBarProps = ComponentProps<typeof ImageEditorTopBar>;

interface Props {
  projectId?: string;
  projectName: TopBarProps["projectName"];
  saveStatus: TopBarProps["saveStatus"];
  onSaveRetry: TopBarProps["onSaveRetry"];
}

/**
 * Phone layout for the Image Editor: canvas fills the viewport, the tool dock
 * becomes a scrollable bottom bar, and the Adjust/Filters/Layers panel opens as a
 * bottom sheet. Drawing/selection work via touch (see ImageEditorCanvas).
 */
export function ImageEditorMobileLayout({ projectId, projectName, saveStatus, onSaveRetry }: Props) {
  const t = useTranslations("auto.componentsImageEditorImageEditorToolbar");
  const activeTool = useImageEditorStore((s) => s.activeTool);
  const setActiveTool = useImageEditorStore((s) => s.setActiveTool);
  const setPendingShape = useImageEditorStore((s) => s.setPendingShape);
  const setAiModalOpen = useImageEditorStore((s) => s.setAiModalOpen);
  const [panelOpen, setPanelOpen] = useState(false);
  const [shapeOpen, setShapeOpen] = useState(false);

  return (
    <div className="flex h-[100dvh] w-screen flex-col overflow-hidden bg-gray-950 text-white">
      <Toaster />
      <ImageEditorTopBar
        projectId={projectId}
        projectName={projectName}
        saveStatus={saveStatus}
        onSaveRetry={onSaveRetry}
      />
      <ImageCropControls />
      <div className="min-h-0 flex-1">
        <ImageEditorCanvas />
      </div>

      {/* Bottom tool bar */}
      <nav className="flex shrink-0 items-center gap-1 overflow-x-auto border-t border-gray-800 bg-gray-900 px-2 py-1.5 [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
        {IMAGE_TOOLS.map((tool) => {
          const Icon = tool.icon;
          const active = activeTool === tool.id && tool.id !== "ai";
          return (
            <button
              key={tool.id}
              type="button"
              aria-label={t(tool.labelKey)}
              onClick={() => {
                if (tool.id === "ai") {
                  setAiModalOpen(true);
                  return;
                }
                if (tool.id === "shape") {
                  setActiveTool("shape");
                  setShapeOpen(true);
                  return;
                }
                setActiveTool(tool.id);
              }}
              className={cn(
                "flex shrink-0 flex-col items-center gap-0.5 rounded-lg px-3 py-1.5 text-[10px] font-medium transition-colors",
                active ? "bg-primary-600 text-white" : "text-gray-400 hover:bg-gray-800",
              )}
            >
              <Icon className="h-5 w-5" aria-hidden />
              <span className="max-w-[56px] truncate">{t(tool.labelKey)}</span>
            </button>
          );
        })}
        <button
          type="button"
          aria-label={t("panels")}
          onClick={() => setPanelOpen(true)}
          className="ms-auto flex shrink-0 flex-col items-center gap-0.5 rounded-lg px-3 py-1.5 text-[10px] font-medium text-gray-400 hover:bg-gray-800"
        >
          <SlidersHorizontal className="h-5 w-5" aria-hidden />
          <span>{t("panels")}</span>
        </button>
      </nav>

      <BottomSheet open={panelOpen} onClose={() => setPanelOpen(false)}>
        <ImageEditorRightPanel />
      </BottomSheet>

      <BottomSheet open={shapeOpen} onClose={() => setShapeOpen(false)} title={t("toolShape")}>
        <div className="grid grid-cols-2 gap-2 p-4">
          {IMAGE_SHAPES.map((s) => (
            <button
              key={s.id}
              type="button"
              onClick={() => {
                setPendingShape(s.id);
                setActiveTool("shape");
                setShapeOpen(false);
              }}
              className="rounded-lg border border-gray-200 px-3 py-3 text-sm font-medium text-gray-800 hover:bg-gray-50"
            >
              {t(s.labelKey)}
            </button>
          ))}
        </div>
      </BottomSheet>

      <AiRemoveBgModal />
    </div>
  );
}
