"use client";

import { useState, FormEvent } from "react";
import { createChannel } from "@/lib/api";
import { X, Hash, Lock } from "lucide-react";

interface CreateChannelModalProps {
  open: boolean;
  onClose: () => void;
  onCreated: (channel: any) => void;
}

export function CreateChannelModal({ open, onClose, onCreated }: CreateChannelModalProps) {
  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const [isPrivate, setIsPrivate] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  if (!open) return null;

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    const trimmed = name.trim().toLowerCase().replace(/\s+/g, "-");
    if (!trimmed) return;

    setLoading(true);
    setError("");
    try {
      const channel = await createChannel(trimmed, description || undefined, isPrivate);
      setName("");
      setDescription("");
      setIsPrivate(false);
      onCreated(channel);
      onClose();
    } catch (err: any) {
      const msg =
        err.response?.data?.error ||
        err.response?.data?.message ||
        err.message ||
        "Failed to create channel";
      setError(typeof msg === "string" ? msg : JSON.stringify(msg));
    } finally {
      setLoading(false);
    }
  };

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/40"
      onClick={onClose}
    >
      <div
        className="w-full max-w-md bg-white rounded-lg shadow-2xl"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="flex items-center justify-between px-6 py-4 border-b border-gray-200">
          <h2 className="text-lg font-bold text-gray-900">Create a channel</h2>
          <button
            onClick={onClose}
            className="p-1 rounded text-gray-400 hover:text-gray-600 hover:bg-gray-100 transition-colors"
          >
            <X size={20} />
          </button>
        </div>

        {/* Body */}
        <form onSubmit={handleSubmit} className="px-6 py-5 space-y-4">
          <p className="text-sm text-gray-500">
            Channels are where your team communicates. They&apos;re best when organized around a topic — e.g., marketing.
          </p>

          {/* Privacy toggle */}
          <div className="flex items-center gap-2 p-3 rounded-md bg-gray-50 border border-gray-200">
            {isPrivate ? <Lock size={18} className="text-gray-500" /> : <Hash size={18} className="text-gray-500" />}
            <div className="flex-1">
              <button
                type="button"
                onClick={() => setIsPrivate(false)}
                className={`block text-sm font-medium ${!isPrivate ? "text-gray-900" : "text-gray-400"}`}
              >
                Public channel
              </button>
              {!isPrivate && <p className="text-xs text-gray-400">Anyone in the workspace can join</p>}
            </div>
            <div className="flex-1">
              <button
                type="button"
                onClick={() => setIsPrivate(true)}
                className={`block text-sm font-medium ${isPrivate ? "text-gray-900" : "text-gray-400"}`}
              >
                Private channel
              </button>
              {isPrivate && <p className="text-xs text-gray-400">Only invited people can join</p>}
            </div>
          </div>

          {/* Name */}
          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-1">
              Channel name
            </label>
            <div className="flex items-center gap-2">
              {isPrivate ? <Lock size={16} className="text-gray-400" /> : <Hash size={16} className="text-gray-400" />}
              <input
                type="text"
                value={name}
                onChange={(e) => setName(e.target.value)}
                placeholder="e.g. marketing"
                autoFocus
                className="flex-1 px-3 py-2 rounded-md border border-gray-300 focus:outline-none focus:ring-2 focus:ring-slack-purple focus:border-transparent text-sm"
              />
            </div>
          </div>

          {/* Description */}
          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-1">
              Description <span className="text-gray-400 font-normal">(optional)</span>
            </label>
            <input
              type="text"
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder="What is this channel about?"
              className="w-full px-3 py-2 rounded-md border border-gray-300 focus:outline-none focus:ring-2 focus:ring-slack-purple focus:border-transparent text-sm"
            />
          </div>

          {error && (
            <div className="p-2 rounded-md bg-red-50 border border-red-200 text-red-700 text-xs">
              {error}
            </div>
          )}

          {/* Actions */}
          <div className="flex justify-end gap-2 pt-2">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 rounded-md text-sm font-medium text-gray-600 hover:bg-gray-100 transition-colors"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={loading || !name.trim()}
              className="px-4 py-2 rounded-md bg-slack-purple text-white text-sm font-semibold hover:bg-slack-darkpurple disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
            >
              {loading ? "Creating..." : "Create"}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}