'use client';

import { useState } from 'react';
import { connectionRequestsService, ConnectionStatus } from '@/services/connection-requests.service';

interface ConnectRequestModalProps {
  isOpen: boolean;
  onClose: () => void;
  agentProfileId: string;
  agentName: string;
  existingStatus?: ConnectionStatus | null;
  onSuccess?: () => void;
}

export function ConnectRequestModal({
  isOpen,
  onClose,
  agentProfileId,
  agentName,
  existingStatus,
  onSuccess,
}: ConnectRequestModalProps) {
  const [message, setMessage] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);

  if (!isOpen) return null;

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSubmitting(true);
    setError(null);

    try {
      await connectionRequestsService.createRequest({
        agentProfileId,
        message: message.trim() || undefined,
      });
      setSuccess(true);
      setMessage('');
      onSuccess?.();
      // Auto close after 2 seconds
      setTimeout(() => {
        onClose();
        setSuccess(false);
      }, 2000);
    } catch (err: unknown) {
      const errorMessage =
        err instanceof Error
          ? err.message
          : (err as { response?: { data?: { message?: string } } })?.response?.data?.message ||
            'Failed to send connection request';
      setError(errorMessage);
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleClose = () => {
    setMessage('');
    setError(null);
    setSuccess(false);
    onClose();
  };

  // If already connected or pending, show status
  if (existingStatus === 'PENDING') {
    return (
      <div className="fixed inset-0 z-50 flex items-center justify-center">
        <div className="absolute inset-0 bg-black/50" onClick={handleClose} />
        <div className="relative bg-white rounded-[20px] p-6 w-full max-w-md mx-4 shadow-xl">
          <div className="text-center">
            <div className="w-16 h-16 bg-yellow-100 rounded-full flex items-center justify-center mx-auto mb-4">
              <svg className="w-8 h-8 text-yellow-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
            </div>
            <h3 className="text-lg font-bold text-[#00293D] mb-2">Request Pending</h3>
            <p className="text-sm text-[#00293D]/70 mb-4">
              Your connection request to {agentName} is pending. Please wait for their response.
            </p>
            <button
              onClick={handleClose}
              className="px-6 py-2 bg-[#00293D] rounded-full text-sm font-semibold text-white hover:bg-[#00293D]/90 transition-colors"
            >
              Close
            </button>
          </div>
        </div>
      </div>
    );
  }

  if (existingStatus === 'ACCEPTED') {
    return (
      <div className="fixed inset-0 z-50 flex items-center justify-center">
        <div className="absolute inset-0 bg-black/50" onClick={handleClose} />
        <div className="relative bg-white rounded-[20px] p-6 w-full max-w-md mx-4 shadow-xl">
          <div className="text-center">
            <div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
              <svg className="w-8 h-8 text-green-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
              </svg>
            </div>
            <h3 className="text-lg font-bold text-[#00293D] mb-2">Already Connected</h3>
            <p className="text-sm text-[#00293D]/70 mb-4">
              You are already connected with {agentName}.
            </p>
            <button
              onClick={handleClose}
              className="px-6 py-2 bg-[#00293D] rounded-full text-sm font-semibold text-white hover:bg-[#00293D]/90 transition-colors"
            >
              Close
            </button>
          </div>
        </div>
      </div>
    );
  }

  // Success state
  if (success) {
    return (
      <div className="fixed inset-0 z-50 flex items-center justify-center">
        <div className="absolute inset-0 bg-black/50" onClick={handleClose} />
        <div className="relative bg-white rounded-[20px] p-6 w-full max-w-md mx-4 shadow-xl">
          <div className="text-center">
            <div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
              <svg className="w-8 h-8 text-green-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
              </svg>
            </div>
            <h3 className="text-lg font-bold text-[#00293D] mb-2">Request Sent!</h3>
            <p className="text-sm text-[#00293D]/70">
              Your connection request has been sent to {agentName}.
            </p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      {/* Backdrop */}
      <div className="absolute inset-0 bg-black/50" onClick={handleClose} />

      {/* Modal */}
      <div className="relative bg-white rounded-[20px] p-6 w-full max-w-md mx-4 shadow-xl">
        {/* Close button */}
        <button
          onClick={handleClose}
          className="absolute top-4 right-4 text-[#00293D]/50 hover:text-[#00293D] transition-colors"
        >
          <svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
          </svg>
        </button>

        {/* Header */}
        <div className="mb-6">
          <h2 className="text-xl font-bold text-[#00293D]">Connect with {agentName}</h2>
          <p className="text-sm text-[#00293D]/70 mt-1">
            Send a connection request to start communicating with this agent.
          </p>
        </div>

        {/* Form */}
        <form onSubmit={handleSubmit}>
          <div className="mb-4">
            <label className="block text-sm font-medium text-[#00293D] mb-2">
              Message (Optional)
            </label>
            <textarea
              value={message}
              onChange={(e) => setMessage(e.target.value)}
              placeholder="Introduce yourself and explain what you're looking for..."
              rows={4}
              maxLength={1000}
              className="w-full px-4 py-3 border border-[#00293D]/20 rounded-[10px] text-sm text-[#00293D] placeholder:text-[#00293D]/40 focus:outline-none focus:border-[#E58625] resize-none"
            />
            <div className="text-xs text-[#00293D]/50 mt-1 text-right">
              {message.length}/1000
            </div>
          </div>

          {error && (
            <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-[10px] text-sm text-red-600">
              {error}
            </div>
          )}

          <div className="flex gap-3">
            <button
              type="button"
              onClick={handleClose}
              className="flex-1 px-4 py-3 border border-[#00293D]/20 rounded-full text-sm font-semibold text-[#00293D] hover:bg-[#00293D]/5 transition-colors"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={isSubmitting}
              className="flex-1 px-4 py-3 bg-[#E58625] rounded-full text-sm font-semibold text-white hover:bg-[#E58625]/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {isSubmitting ? 'Sending...' : 'Send Request'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
