"use client";

import { useState, useRef, useEffect } from "react";
import { setCustomStatus } from "@/lib/api";
import { Smile, X, Clock } from "lucide-react";

interface CustomStatusPickerProps {
  onSet?: (emoji: string, text: string) => void;
  onClose?: () => void;
}

const QUICK_EMOJIS = ["😀", "👍", "🔥", "🎉", "☕", "📅", "🏃", "🤔", "📊", "🏠", "✈️", "🏥"];

const EXPIRATION_OPTIONS = [
  { label: "Don't clear", value: "" },
  { label: "30 minutes", value: "30" },
  { label: "1 hour", value: "60" },
  { label: "4 hours", value: "240" },
  { label: "Today", value: "today" },
  { label: "This week", value: "week" },
];

export function CustomStatusPicker({ onSet, onClose }: CustomStatusPickerProps) {
  const [emoji, setEmoji] = useState("😀");
  const [text, setText] = useState("");
  const [expiration, setExpiration] = useState("");
  const [showEmojis, setShowEmojis] = useState(false);
  const [saving, setSaving] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
        onClose?.();
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, [onClose]);

  const handleSave = () => {
    setSaving(true);
    const expiresAt = expiration ? new Date(Date.now() + (parseInt(expiration) || 0) * 60000).toISOString() : undefined;
    setCustomStatus(emoji, text.trim(), expiresAt)
      .then(() => {
        onSet?.(emoji, text.trim());
        onClose?.();
      })
      .catch(console.error)
      .finally(() => setSaving(false));
  };

  const handleClear = () => {
    setCustomStatus("", "")
      .then(() => {
        onSet?.("", "");
        onClose?.();
      })
      .catch(console.error);
  };

  return (
    <div
      ref={containerRef}
      className="w-72 bg-white rounded-lg shadow-xl border border-gray-200 overflow-hidden"
    >
      {/* Header */}
      <div className="flex items-center justify-between px-4 py-3 border-b border-gray-100">
        <h3 className="font-bold text-sm text-gray-800">Set a status</h3>
        {onClose && (
          <button
            onClick={onClose}
            className="p-1 rounded text-gray-400 hover:bg-gray-100 hover:text-gray-600"
          >
            <X size={14} />
          </button>
        )}
      </div>

      {/* Input row */}
      <div className="p-3">
        <div className="flex gap-2">
          {/* Emoji button */}
          <div className="relative">
            <button
              onClick={() => setShowEmojis(!showEmojis)}
              className="w-10 h-10 flex items-center justify-center text-xl rounded-md border border-gray-300 hover:border-slack-purple transition-colors"
            >
              {emoji}
            </button>
            {showEmojis && (
              <div className="absolute top-full left-0 mt-1 w-48 bg-white rounded-lg shadow-lg border border-gray-200 p-2 z-10">
                <div className="grid grid-cols-6 gap-1">
                  {QUICK_EMOJIS.map((e) => (
                    <button
                      key={e}
                      onClick={() => {
                        setEmoji(e);
                        setShowEmojis(false);
                      }}
                      className="w-7 h-7 flex items-center justify-center text-lg rounded hover:bg-gray-100"
                    >
                      {e}
                    </button>
                  ))}
                </div>
              </div>
            )}
          </div>

          {/* Text input */}
          <input
            type="text"
            value={text}
            onChange={(e) => setText(e.target.value)}
            placeholder="What are you working on?"
            className="flex-1 px-3 py-2 rounded-md border border-gray-300 focus:outline-none focus:ring-2 focus:ring-slack-purple text-sm"
          />
        </div>

        {/* Expiration */}
        <div className="mt-3">
          <label className="block text-xs font-semibold text-gray-500 mb-1 flex items-center gap-1">
            <Clock size={12} />
            Clear after
          </label>
          <select
            value={expiration}
            onChange={(e) => setExpiration(e.target.value)}
            className="w-full px-3 py-1.5 rounded-md border border-gray-300 focus:outline-none focus:ring-2 focus:ring-slack-purple text-sm bg-white"
          >
            {EXPIRATION_OPTIONS.map((opt) => (
              <option key={opt.value} value={opt.value}>{opt.label}</option>
            ))}
          </select>
        </div>

        {/* Buttons */}
        <div className="flex gap-2 mt-4">
          <button
            onClick={handleSave}
            disabled={saving}
            className="flex-1 px-4 py-2 rounded-md bg-slack-purple text-white text-sm font-medium hover:bg-slack-darkpurple transition-colors disabled:opacity-50"
          >
            {saving ? "Saving..." : "Save"}
          </button>
          <button
            onClick={handleClear}
            className="px-4 py-2 rounded-md border border-gray-300 text-sm font-medium text-gray-600 hover:bg-gray-50 transition-colors"
          >
            Clear
          </button>
        </div>
      </div>
    </div>
  );
}