'use client';

import { useState } from 'react';
import { useSession } from 'next-auth/react';
import { useRouter, usePathname } from 'next/navigation';

type ConnectionStatus = 'PENDING' | 'ACCEPTED' | 'REJECTED' | null;

interface StatusButtonsProps {
  isAvailable?: boolean;
  connectionStatus?: ConnectionStatus;
  onToggleAvailability?: () => void;
  onConnectClick?: () => void; // Callback when Connect button is clicked (for opening modal)
  onUnlinkClick?: () => void; // Callback when Unlink button is clicked
  showToggle?: boolean; // If true, show as toggle (for agent's own dashboard)
}

export function StatusButtons({
  isAvailable = true,
  connectionStatus = null,
  onToggleAvailability,
  onConnectClick,
  onUnlinkClick,
  showToggle = false
}: StatusButtonsProps) {
  const { data: session } = useSession();
  const router = useRouter();
  const pathname = usePathname();
  const [isUnlinking, setIsUnlinking] = useState(false);

  // Handle connect click - require login if not authenticated
  const handleConnectClick = () => {
    if (!isAvailable) return; // Don't do anything if unavailable

    if (!session) {
      // Store the current page to redirect back after login
      const returnUrl = encodeURIComponent(pathname);
      router.push(`/login?callbackUrl=${returnUrl}`);
      return;
    }

    // Call the onConnectClick callback if provided
    onConnectClick?.();
  };

  // Handle unlink click
  const handleUnlinkClick = async () => {
    if (isUnlinking) return;
    setIsUnlinking(true);
    try {
      await onUnlinkClick?.();
    } finally {
      setIsUnlinking(false);
    }
  };

  // Render the appropriate button based on connection status
  const renderConnectionButton = () => {
    // If PENDING - show yellow Pending button (disabled)
    if (connectionStatus === 'PENDING') {
      return (
        <button
          disabled
          className="px-5 py-1.5 text-[#92600f] text-sm rounded-[15px] bg-[#fef3c7] cursor-not-allowed font-fractul"
        >
          Pending
        </button>
      );
    }

    // If ACCEPTED - show Unlink button
    if (connectionStatus === 'ACCEPTED') {
      return (
        <button
          onClick={handleUnlinkClick}
          disabled={isUnlinking}
          className="px-5 py-1.5 text-white text-sm rounded-[15px] bg-red-500 hover:bg-red-600 transition-colors font-fractul disabled:opacity-50"
        >
          {isUnlinking ? 'Unlinking...' : 'Unlink'}
        </button>
      );
    }

    // Default: No request or REJECTED - show Connect button
    return (
      <button
        onClick={handleConnectClick}
        disabled={!isAvailable}
        className={`px-5 py-1.5 text-white text-sm rounded-[15px] transition-colors font-fractul ${
          isAvailable
            ? 'bg-[#e58625] hover:bg-[#d47720] cursor-pointer'
            : 'bg-[#00293d] cursor-not-allowed opacity-70'
        }`}
      >
        Connect
      </button>
    );
  };

  // If showToggle is true, render both options as a toggle selector (for agent dashboard)
  if (showToggle) {
    return (
      <div className="w-full max-w-[354px] lg:max-w-none space-y-2">
        {/* Available Option */}
        <button
          onClick={() => !isAvailable && onToggleAvailability?.()}
          className={`w-full flex items-center border rounded-[15px] h-[50px] px-4 transition-colors ${
            isAvailable
              ? 'border-green-500 bg-green-50'
              : 'border-[#00293d]/10 hover:border-[#00293d]/20'
          }`}
        >
          <div className="flex items-center gap-2 flex-1">
            <span className={`w-3 h-3 rounded-full ${
              isAvailable ? 'bg-green-500' : 'bg-white border border-gray-400'
            }`} />
            <span className="text-sm font-bold text-[#00293d] font-fractul">Available.</span>
          </div>
          {isAvailable && (
            <span className="text-xs text-green-600 font-medium">Active</span>
          )}
        </button>

        {/* Unavailable Option */}
        <button
          onClick={() => isAvailable && onToggleAvailability?.()}
          className={`w-full flex items-center border rounded-[15px] h-[50px] px-4 transition-colors ${
            !isAvailable
              ? 'border-[#00293d] bg-[#00293d]/5'
              : 'border-[#00293d]/10 hover:border-[#00293d]/20'
          }`}
        >
          <div className="flex items-center gap-2 flex-1">
            <span className={`w-3 h-3 rounded-full ${
              !isAvailable ? 'bg-[#00293d]' : 'bg-white border border-gray-400'
            }`} />
            <span className="text-sm font-bold text-[#00293d] font-fractul">Unavailable.</span>
          </div>
          {!isAvailable && (
            <span className="text-xs text-[#00293d]/70 font-medium">Active</span>
          )}
        </button>
      </div>
    );
  }

  // Public view - show single status with Connect/Pending/Unlink button
  return (
    <div className="w-full max-w-[354px] lg:max-w-none">
      <div className="flex items-center border border-[#00293d]/10 rounded-[15px] h-[50px] px-4">
        <div className="flex items-center gap-2 flex-1">
          <span className={`w-3 h-3 rounded-full ${
            isAvailable ? 'bg-green-500' : 'bg-white border border-gray-400'
          }`} />
          <span className="text-sm font-bold text-[#00293d] font-fractul">
            {isAvailable ? 'Available.' : 'Unavailable.'}
          </span>
        </div>
        {renderConnectionButton()}
      </div>
    </div>
  );
}
