"use client";

import { useEffect, useState } from "react";
import {
  getScheduledMessages,
  scheduleMessage,
  deleteScheduledMessage,
  ScheduledMessage,
} from "@/lib/api";
import { Clock, Plus, Trash2, X, Send } from "lucide-react";

interface ScheduledMessagesProps {
  channelId?: string;
}

export function ScheduledMessages({ channelId }: ScheduledMessagesProps) {
  const [messages, setMessages] = useState<ScheduledMessage[]>([]);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [text, setText] = useState("");
  const [scheduledAt, setScheduledAt] = useState("");
  const [targetChannel, setTargetChannel] = useState(channelId || "");
  const [scheduling, setScheduling] = useState(false);
  const [error, setError] = useState("");

  const loadMessages = () => {
    setLoading(true);
    getScheduledMessages()
      .then(setMessages)
      .catch(console.error)
      .finally(() => setLoading(false));
  };

  useEffect(() => {
    loadMessages();
  }, []);

  useEffect(() => {
    if (channelId) setTargetChannel(channelId);
  }, [channelId]);

  const handleSchedule = () => {
    if (!text.trim() || !scheduledAt || !targetChannel) {
      setError("Please fill in all fields.");
      return;
    }
    setError("");
    setScheduling(true);
    scheduleMessage(targetChannel, text.trim(), scheduledAt)
      .then(() => {
        setText("");
        setScheduledAt("");
        setShowForm(false);
        loadMessages();
      })
      .catch((e) => setError(e.message || "Failed to schedule message"))
      .finally(() => setScheduling(false));
  };

  const handleDelete = (id: string) => {
    deleteScheduledMessage(id)
      .then(() => {
        setMessages((prev) => prev.filter((m) => m.id !== id));
      })
      .catch(console.error);
  };

  const formatDate = (dateStr: string) => {
    try {
      return new Date(dateStr).toLocaleString();
    } catch {
      return dateStr;
    }
  };

  return (
    <div className="space-y-3">
      {/* Header */}
      <div className="flex items-center justify-between">
        <h4 className="text-xs font-semibold text-gray-500 uppercase flex items-center gap-1.5">
          <Clock size={14} />
          Scheduled ({messages.length})
        </h4>
        <button
          onClick={() => setShowForm(!showForm)}
          className="p-1 rounded text-gray-400 hover:text-slack-purple hover:bg-gray-100 transition-colors"
        >
          {showForm ? <X size={14} /> : <Plus size={14} />}
        </button>
      </div>

      {/* Form */}
      {showForm && (
        <div className="p-3 rounded-lg border border-gray-200 bg-gray-50 space-y-2">
          <textarea
            value={text}
            onChange={(e) => setText(e.target.value)}
            placeholder="Message to schedule..."
            rows={2}
            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 resize-none"
          />
          <div className="flex gap-2">
            <input
              type="text"
              value={targetChannel}
              onChange={(e) => setTargetChannel(e.target.value)}
              placeholder="Channel ID"
              className="flex-1 px-2 py-1.5 rounded-md border border-gray-300 focus:outline-none focus:ring-2 focus:ring-slack-purple text-xs"
            />
            <input
              type="datetime-local"
              value={scheduledAt}
              onChange={(e) => setScheduledAt(e.target.value)}
              className="px-2 py-1.5 rounded-md border border-gray-300 focus:outline-none focus:ring-2 focus:ring-slack-purple text-xs"
            />
          </div>
          {error && <p className="text-xs text-slack-red">{error}</p>}
          <button
            onClick={handleSchedule}
            disabled={scheduling}
            className="flex items-center gap-1 px-3 py-1.5 rounded-md bg-slack-purple text-white text-xs font-medium hover:bg-slack-darkpurple transition-colors disabled:opacity-50"
          >
            <Send size={12} />
            {scheduling ? "Scheduling..." : "Schedule"}
          </button>
        </div>
      )}

      {/* List */}
      {loading ? (
        <div className="text-xs text-gray-400 animate-pulse">Loading scheduled messages...</div>
      ) : messages.length === 0 ? (
        <p className="text-xs text-gray-400">No scheduled messages.</p>
      ) : (
        <div className="space-y-2 max-h-48 overflow-y-auto">
          {messages.map((msg) => (
            <div
              key={msg.id}
              className="group p-2 rounded-md bg-gray-50 border border-gray-100"
            >
              <div className="flex items-start justify-between gap-2">
                <div className="flex-1 min-w-0">
                  <p className="text-xs text-gray-700 break-words">{msg.text}</p>
                  <p className="text-xs text-gray-400 mt-0.5">
                    {msg.channel_name || msg.channel_id} · {formatDate(msg.scheduled_at)}
                  </p>
                </div>
                <button
                  onClick={() => handleDelete(msg.id)}
                  className="opacity-0 group-hover:opacity-100 text-gray-400 hover:text-slack-red p-0.5 rounded transition-all flex-shrink-0"
                >
                  <Trash2 size={12} />
                </button>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}