"use client";

import { useEffect, useState, useCallback } from "react";
import {
  getSharedChannels,
  shareChannel,
  acceptSharedChannel,
  SharedChannel,
} from "@/lib/api";
import { Globe, Plus, Check, X, RefreshCw, Share2, Clock, CheckCircle2 } from "lucide-react";

export function SharedChannels() {
  const [channels, setChannels] = useState<SharedChannel[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [showForm, setShowForm] = useState(false);
  const [channelId, setChannelId] = useState("");
  const [targetDomain, setTargetDomain] = useState("");
  const [sharing, setSharing] = useState(false);
  const [accepting, setAccepting] = useState<string | null>(null);

  const loadChannels = useCallback(() => {
    setLoading(true);
    setError("");
    getSharedChannels()
      .then((data) => setChannels(Array.isArray(data) ? data : []))
      .catch((err) => {
        console.error("Failed to load shared channels:", err);
        setError("Failed to load shared channels");
      })
      .finally(() => setLoading(false));
  }, []);

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

  const handleShare = () => {
    if (!channelId.trim() || !targetDomain.trim()) return;
    setSharing(true);
    setError("");
    shareChannel(channelId.trim(), targetDomain.trim())
      .then((newChannel) => {
        setChannels((prev) => [...prev, newChannel]);
        setChannelId("");
        setTargetDomain("");
        setShowForm(false);
      })
      .catch((err) => {
        console.error("Failed to share channel:", err);
        setError("Failed to share channel");
      })
      .finally(() => setSharing(false));
  };

  const handleAccept = (inviteId: string) => {
    setAccepting(inviteId);
    acceptSharedChannel(inviteId)
      .then((updated) => {
        setChannels((prev) =>
          prev.map((ch) => (ch.id === updated.id ? updated : ch))
        );
      })
      .catch((err) => console.error("Failed to accept shared channel:", err))
      .finally(() => setAccepting(null));
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case "pending":
        return (
          <span className="inline-flex items-center gap-0.5 text-[10px] px-2 py-0.5 rounded-full bg-slack-yellow/10 text-slack-yellow font-medium">
            <Clock size={9} />
            Pending
          </span>
        );
      case "accepted":
      case "active":
        return (
          <span className="inline-flex items-center gap-0.5 text-[10px] px-2 py-0.5 rounded-full bg-slack-green/10 text-slack-green font-medium">
            <CheckCircle2 size={9} />
            Active
          </span>
        );
      case "rejected":
        return (
          <span className="text-[10px] px-2 py-0.5 rounded-full bg-slack-red/10 text-slack-red font-medium">
            Rejected
          </span>
        );
      default:
        return (
          <span className="text-[10px] px-2 py-0.5 rounded-full bg-gray-100 text-gray-400 font-medium">
            {status}
          </span>
        );
    }
  };

  return (
    <div className="space-y-4">
      {/* Header */}
      <div className="flex items-center justify-between">
        <h3 className="text-sm font-semibold text-gray-700 flex items-center gap-1.5">
          <Globe size={16} className="text-slack-purple" />
          Shared Channels ({channels.length})
        </h3>
        <button
          onClick={() => setShowForm(!showForm)}
          className="flex items-center gap-1 px-2 py-1 rounded-md text-xs text-slack-purple hover:bg-slack-purple/10 transition-colors"
        >
          {showForm ? <X size={14} /> : <Plus size={14} />}
          {showForm ? "Cancel" : "Share Channel"}
        </button>
      </div>

      {/* Form */}
      {showForm && (
        <div className="p-4 rounded-lg border border-gray-200 bg-gray-50 space-y-2">
          <input
            type="text"
            value={channelId}
            onChange={(e) => setChannelId(e.target.value)}
            placeholder="Channel ID to share"
            className="w-full px-3 py-2 rounded-md border border-gray-300 text-sm focus:outline-none focus:ring-2 focus:ring-slack-purple"
          />
          <input
            type="text"
            value={targetDomain}
            onChange={(e) => setTargetDomain(e.target.value)}
            placeholder="Target domain (e.g. partner.com)"
            className="w-full px-3 py-2 rounded-md border border-gray-300 text-sm focus:outline-none focus:ring-2 focus:ring-slack-purple"
          />
          {error && <p className="text-xs text-slack-red">{error}</p>}
          <button
            onClick={handleShare}
            disabled={sharing || !channelId.trim() || !targetDomain.trim()}
            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"
          >
            <Share2 size={12} />
            {sharing ? "Sharing..." : "Share Channel"}
          </button>
        </div>
      )}

      {/* List */}
      {loading ? (
        <div className="flex items-center justify-center text-gray-400 py-8">
          <RefreshCw size={18} className="animate-pulse" />
        </div>
      ) : error ? (
        <div className="text-sm text-slack-red py-4 text-center">
          {error}
          <button
            onClick={loadChannels}
            className="ml-2 text-slack-purple hover:underline"
          >
            Retry
          </button>
        </div>
      ) : channels.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-12 text-gray-400">
          <Globe size={48} className="mb-3 opacity-50" />
          <p className="text-sm">No shared channels yet.</p>
          <p className="text-xs mt-1">Share a channel with external organizations via Connect.</p>
        </div>
      ) : (
        <div className="space-y-3">
          {channels.map((ch) => (
            <div
              key={ch.id}
              className="group p-4 rounded-lg border border-gray-200 bg-white shadow-sm hover:border-slack-purple/30 transition-colors"
            >
              <div className="flex items-start justify-between gap-3">
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2">
                    <Share2 size={14} className="text-slack-purple" />
                    <h4 className="text-sm font-semibold text-gray-800">
                      #{ch.name}
                    </h4>
                    {getStatusBadge(ch.status)}
                  </div>
                  <div className="mt-2 space-y-1 text-xs text-gray-500">
                    <p className="flex items-center gap-1">
                      <Globe size={11} />
                      Shared with: <span className="font-medium">{ch.shared_with_domain}</span>
                    </p>
                    {ch.shared_at && (
                      <p>
                        Shared: {new Date(ch.shared_at).toLocaleDateString("en-US", {
                          month: "short",
                          day: "numeric",
                          year: "numeric",
                        })}
                      </p>
                    )}
                    {ch.accepted_at && (
                      <p>
                        Accepted: {new Date(ch.accepted_at).toLocaleDateString("en-US", {
                          month: "short",
                          day: "numeric",
                          year: "numeric",
                        })}
                      </p>
                    )}
                  </div>
                </div>
                {ch.status === "pending" && (
                  <button
                    onClick={() => handleAccept(ch.id)}
                    disabled={accepting === ch.id}
                    className="flex items-center gap-1 px-3 py-1.5 rounded-md bg-slack-green text-white text-xs font-medium hover:bg-slack-green/90 transition-colors disabled:opacity-50"
                  >
                    <Check size={12} />
                    {accepting === ch.id ? "Accepting..." : "Accept"}
                  </button>
                )}
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

export default SharedChannels;