"use client";

import { useRef, useState, type ChangeEvent } from "react";
import { Box, HardDrive, Search, UploadCloud } from "lucide-react";
import { useTranslations } from "next-intl";

import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { MUSIC_GENRE_CARDS } from "@/lib/audio-music-genres";
import { useStudioStore } from "@/lib/studio-store";
import { cn } from "@/lib/utils";

export function AudioSidebarMusicTab() {
  const t = useTranslations("auto.componentsStudioSidebarAudioSidebarMusicTab");
  const inputRef = useRef<HTMLInputElement>(null);
  const setAudioTrack = useStudioStore((state) => state.setAudioTrack);
  const [includeTemplateSfx, setIncludeTemplateSfx] = useState(true);
  const [search, setSearch] = useState("");
  const [activeGenre, setActiveGenre] = useState("all");

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

    const reader = new FileReader();
    reader.onload = () => {
      if (typeof reader.result === "string") {
        setAudioTrack(file.name, reader.result);
      }
    };
    reader.readAsDataURL(file);
    event.target.value = "";
  };

  const query = search.trim().toLowerCase();
  const genres = query
    ? MUSIC_GENRE_CARDS.filter((genre) =>
        genre.name.toLowerCase().includes(query)
      )
    : MUSIC_GENRE_CARDS;

  return (
    <div className="space-y-4">
      <input
        ref={inputRef}
        type="file"
        accept="audio/*"
        className="hidden"
        onChange={handleFileChange}
      />

      <div className="space-y-2">
        <SourceButton
          icon={UploadCloud}
          label={t("upload")}
          onClick={() => inputRef.current?.click()}
        />
        <SourceButton icon={Box} label="Dropbox" onClick={() => undefined} />
        <SourceButton
          icon={HardDrive}
          label="Google Drive"
          onClick={() => undefined}
        />
      </div>

      <div className="flex items-center justify-between gap-2">
        <span className="text-[11px] leading-snug text-gray-500">
          {t("includeTemplateSfx")}
        </span>
        <Switch
          checked={includeTemplateSfx}
          onCheckedChange={setIncludeTemplateSfx}
          aria-label={t("includeTemplateSfx")}
        />
      </div>

      <div className="relative">
        <Search
          className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-gray-500"
          aria-hidden
        />
        <input
          type="search"
          placeholder={t("searchPlaceholder")}
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          className="h-9 w-full rounded-lg border border-gray-200 bg-white pl-8 pr-3 text-xs text-white placeholder:text-gray-400 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
        />
      </div>

      <Tabs defaultValue="library" className="w-full">
        <TabsList className="grid h-8 w-full grid-cols-2 rounded-full bg-gray-100 p-0.5">
          <TabsTrigger
            value="library"
            className="rounded-full text-[11px] data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-500"
          >
            {t("musicLibrary")}
          </TabsTrigger>
          <TabsTrigger
            value="my-music"
            className="rounded-full text-[11px] data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-500"
          >
            {t("myMusic")}
          </TabsTrigger>
        </TabsList>

        <TabsContent value="library" className="mt-3">
          <div className="grid grid-cols-2 gap-2">
            {genres.map((genre) => (
              <button
                key={genre.id}
                type="button"
                onClick={() => setActiveGenre(genre.id)}
                className={cn(
                  "flex h-[70px] items-center justify-center rounded-lg px-2 text-center transition-transform hover:scale-[1.02] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500",
                  activeGenre === genre.id && "ring-2 ring-blue-500 ring-offset-1 ring-offset-white"
                )}
                style={{
                  background: `linear-gradient(135deg, ${genre.gradientFrom}, ${genre.gradientTo})`,
                }}
              >
                <span className="text-[11px] font-bold leading-tight text-white">
                  {genre.name}
                </span>
              </button>
            ))}
          </div>
        </TabsContent>

        <TabsContent value="my-music" className="mt-3">
          <div className="flex flex-col items-center rounded-xl border border-dashed border-gray-200 bg-white/40 px-3 py-8 text-center">
            <UploadCloud className="h-8 w-8 text-gray-500" aria-hidden />
            <p className="mt-3 text-xs text-gray-500">{t("uploadOwnMusic")}</p>
            <Button
              type="button"
              size="sm"
              variant="outline"
              className="mt-3 h-8 border-gray-300 bg-white text-xs text-gray-700 hover:bg-gray-50"
              onClick={() => inputRef.current?.click()}
            >
              {t("upload")}
            </Button>
          </div>
        </TabsContent>
      </Tabs>
    </div>
  );
}

function SourceButton({
  icon: Icon,
  label,
  onClick,
}: {
  icon: typeof UploadCloud;
  label: string;
  onClick: () => void;
}) {
  return (
    <button
      type="button"
      onClick={onClick}
      className="flex w-full items-center gap-2 rounded-lg border border-gray-200 bg-white px-3 py-2.5 text-left text-sm text-gray-200 transition-colors hover:border-blue-300 hover:bg-blue-50 hover:text-gray-900 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
    >
      <Icon className="h-4 w-4 shrink-0 text-gray-500" aria-hidden />
      {label}
    </button>
  );
}
