"use client";

import { useState, useRef } from "react";
import { Upload } from "lucide-react";
import type { AppIcon } from "@/lib/types";
import { LUCIDE_ICONS, LUCIDE_ICON_NAMES } from "./lucideIcons";

const COMMON_EMOJIS = [
  "🚀", "🌐", "💻", "🖥️", "📱", "📊", "📈", "📉",
  "🗄️", "🔧", "⚙️", "🛠️", "🔒", "🔑", "🛡️", "🔔",
  "📧", "💬", "📝", "📋", "📁", "📂", "🗂️", "📦",
  "🎮", "🎵", "🎬", "📷", "🎨", "🖌️", "✏️", "📐",
  "🏠", "🏢", "🏗️", "🏭", "🚗", "✈️", "🚢", "🚚",
  "💰", "💳", "🛒", "🎓", "📚", "📖", "📰", "🗞️",
  "❤️", "⭐", "🔥", "⚡", "☀️", "🌙", "🌍", "🧭",
  "👥", "👤", "🤖", "👾", "🐳", "🐙", "🦊", "🐧",
  "✅", "❌", "⚠️", "ℹ️", "🔴", "🟢", "🔵", "🟡",
];

type TabId = "lucide" | "emoji" | "upload";

interface IconSelectorProps {
  value: AppIcon;
  onChange: (icon: AppIcon) => void;
  onUpload: (file: File) => Promise<string>;
}

export function IconSelector({ value, onChange, onUpload }: IconSelectorProps) {
  const [tab, setTab] = useState<TabId>(value.type === "upload" ? "upload" : value.type === "emoji" ? "emoji" : "lucide");
  const [search, setSearch] = useState("");
  const [uploading, setUploading] = useState(false);
  const fileRef = useRef<HTMLInputElement>(null);

  const filteredIcons = search
    ? LUCIDE_ICON_NAMES.filter((name) => name.toLowerCase().includes(search.toLowerCase()))
    : LUCIDE_ICON_NAMES;

  const handleFileSelect = async (file: File) => {
    setUploading(true);
    try {
      const url = await onUpload(file);
      onChange({ type: "upload", value: url });
    } finally {
      setUploading(false);
    }
  };

  const tabs: { id: TabId; label: string }[] = [
    { id: "lucide", label: "Icons" },
    { id: "emoji", label: "Emoji" },
    { id: "upload", label: "Upload" },
  ];

  return (
    <div className="space-y-3">
      {/* Tab buttons */}
      <div className="flex gap-1">
        {tabs.map((t) => (
          <button
            key={t.id}
            type="button"
            onClick={() => setTab(t.id)}
            className={`rounded-lg px-3 py-1.5 text-sm font-medium transition-colors ${
              tab === t.id
                ? "bg-zinc-200 text-zinc-900 dark:bg-zinc-700 dark:text-zinc-100"
                : "text-zinc-500 hover:bg-zinc-100 dark:text-zinc-400 dark:hover:bg-zinc-800"
            }`}
          >
            {t.label}
          </button>
        ))}
      </div>

      {/* Lucide tab */}
      {tab === "lucide" && (
        <div className="space-y-2">
          <input
            type="text"
            placeholder="Search icons..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="w-full rounded-lg border border-zinc-200 px-3 py-1.5 text-sm dark:border-zinc-700 dark:bg-zinc-800 dark:text-zinc-100"
          />
          <div className="grid max-h-48 grid-cols-8 gap-1 overflow-y-auto">
            {filteredIcons.map((name) => {
              const Icon = LUCIDE_ICONS[name];
              const selected = value.type === "lucide" && value.value === name;
              return (
                <button
                  key={name}
                  type="button"
                  title={name}
                  onClick={() => onChange({ type: "lucide", value: name })}
                  className={`flex items-center justify-center rounded-lg p-2 transition-colors ${
                    selected
                      ? "bg-blue-100 text-blue-700 ring-2 ring-blue-500 dark:bg-blue-900/40 dark:text-blue-300"
                      : "text-zinc-600 hover:bg-zinc-100 dark:text-zinc-400 dark:hover:bg-zinc-800"
                  }`}
                >
                  <Icon size={18} />
                </button>
              );
            })}
          </div>
        </div>
      )}

      {/* Emoji tab */}
      {tab === "emoji" && (
        <div className="grid max-h-48 grid-cols-8 gap-1 overflow-y-auto">
          {COMMON_EMOJIS.map((emoji) => {
            const selected = value.type === "emoji" && value.value === emoji;
            return (
              <button
                key={emoji}
                type="button"
                onClick={() => onChange({ type: "emoji", value: emoji })}
                className={`flex items-center justify-center rounded-lg p-2 text-lg transition-colors ${
                  selected
                    ? "bg-blue-100 ring-2 ring-blue-500 dark:bg-blue-900/40"
                    : "hover:bg-zinc-100 dark:hover:bg-zinc-800"
                }`}
              >
                {emoji}
              </button>
            );
          })}
        </div>
      )}

      {/* Upload tab */}
      {tab === "upload" && (
        <div
          className="flex cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed border-zinc-300 p-6 text-zinc-500 transition-colors hover:border-blue-400 hover:text-blue-500 dark:border-zinc-600 dark:text-zinc-400 dark:hover:border-blue-500"
          onClick={() => fileRef.current?.click()}
        >
          <Upload size={24} />
          <span className="text-sm">
            {uploading ? "Uploading..." : "Click to select an image"}
          </span>
          {value.type === "upload" && value.value && (
            <img src={value.value} alt="Current icon" className="mt-2 h-10 w-10 rounded" />
          )}
          <input
            ref={fileRef}
            type="file"
            accept="image/*"
            className="hidden"
            onChange={(e) => {
              const file = e.target.files?.[0];
              if (file) handleFileSelect(file);
            }}
          />
        </div>
      )}
    </div>
  );
}
