'use client';

import { useState, useEffect } from 'react';
import { Smartphone, CheckCircle2, XCircle, RefreshCw, Trash2, Plug } from 'lucide-react';
import { cn } from '@/lib/utils';

interface PhoneGatewayCardProps {
  onTestConnection?: () => void;
  testing?: boolean;
}

export default function PhoneGatewayCard({ onTestConnection, testing }: PhoneGatewayCardProps) {
  const [connected, setConnected] = useState<boolean | null>(null);
  const [config, setConfig] = useState<any | null>(null);

  useEffect(() => {
    async function loadConfig() {
      try {
        const res = await fetch('/api/phone-gateway/config');
        if (res.ok) {
          const data = await res.json();
          setConfig(data.config);
          setConnected(!!data.config);
        }
      } catch (err) {
        console.error('Failed to load phone gateway config:', err);
        setConnected(false);
      }
    }
    loadConfig();
  }, []);

  const handleTest = async () => {
    if (onTestConnection) {
      onTestConnection();
    }
    // Re-fetch config after test
    setTimeout(async () => {
      try {
        const res = await fetch('/api/phone-gateway/config');
        if (res.ok) {
          const data = await res.json();
          setConfig(data.config);
          setConnected(!!data.config);
        }
      } catch (err) {
        console.error('Failed to reload phone gateway config:', err);
      }
    }, 1000);
  };

  const handleDisconnect = async () => {
    if (confirm('Are you sure you want to disconnect your Android phone?')) {
      // Clear config from server
      try {
        await fetch('/api/phone-gateway/save', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            host: '',
            port: '8080',
            username: '',
            label: '',
            mode: 'local',
          }),
        });
        setConnected(false);
        setConfig(null);
      } catch (err) {
        alert('Failed to disconnect. Please try again.');
      }
    }
  };

  const handleReconfigure = () => {
    window.location.href = '/connect-phone';
  };

  return (
    <div className="card">
      {/* Card Header */}
      <div className="flex items-center justify-between border-b border-slate-700/50 px-6 py-4">
        <div className="flex items-center gap-3">
          <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-cyan-500/10">
            <Smartphone className="w-4 h-4 text-cyan-400" />
          </div>
          <div>
            <h3 className="font-semibold text-white">Android Phone Gateway</h3>
            <p className="text-xs text-slate-500">
              Connect your Android phone to send SMS for free
            </p>
          </div>
        </div>
      </div>

      {/* Card Content */}
      <div className="p-6 space-y-4">
        {connected ? (
          /* Connected State */
          <>
            <div className="flex items-center gap-3 p-4 rounded-lg bg-green-500/10 border border-green-500/20">
              <CheckCircle2 className="w-5 h-5 text-green-400" />
              <div>
                <p className="font-semibold text-green-400">Connected</p>
                {config?.label && (
                  <p className="text-sm text-slate-400">
                    {config.label}
                  </p>
                )}
                {config?.mode === 'local' && (
                  <p className="text-xs text-slate-500 font-mono mt-1">
                    {config.host}:{config.port}
                  </p>
                )}
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4 mt-4">
              <button
                onClick={handleTest}
                disabled={testing}
                className={cn(
                  'flex items-center justify-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors',
                  testing ? 'opacity-50 cursor-not-allowed' : 'bg-slate-800/50 text-slate-300 hover:bg-slate-700/50'
                )}
              >
                {testing ? (
                  <div className="w-4 h-4 border-2 border-white/30 border-t-transparent animate-spin rounded-full" />
                ) : (
                  <RefreshCw className="w-4 h-4" />
                )}
                Test Connection
              </button>
              <button
                onClick={handleDisconnect}
                className="flex items-center justify-center gap-2 px-4 py-2 rounded-lg text-sm font-medium bg-red-500/10 text-red-400 border border-red-500/20 hover:bg-red-500/20 transition-colors"
              >
                <Trash2 className="w-4 h-4" />
                Disconnect
              </button>
            </div>

            <div className="mt-4 p-4 rounded-lg bg-slate-800/30 border border-slate-700/30">
              <div className="flex items-center gap-2 text-sm">
                <Plug className="w-4 h-4 text-cyan-400" />
                <p className="text-slate-300">
                  Your phone is acting as the SMS gateway. Messages sent through
                  CloseBot will go through your Android device.
                </p>
              </div>
              <div className="mt-3 flex items-center gap-2 text-xs text-slate-500">
                <div className="w-1.5 h-1.5 rounded-full bg-green-500" />
                <span>Free messaging (no carrier fees)</span>
              </div>
            </div>
          </>
        ) : (
          /* Not Connected State */
          <div className="text-center space-y-4 py-4">
            <div className="w-16 h-16 mx-auto rounded-full bg-slate-800/50 flex items-center justify-center mb-4">
              <XCircle className="w-8 h-8 text-slate-600" />
            </div>
            <div>
              <p className="text-lg font-medium text-slate-300 mb-2">
                No Android phone connected
              </p>
              <p className="text-sm text-slate-500 mb-4">
                Connect your Android phone to use it as a free SMS gateway instead
                of Twilio.
              </p>
              <button
                onClick={handleReconfigure}
                className="w-full bg-cyan-500 text-white font-semibold py-3 rounded-lg hover:bg-cyan-600 transition-colors"
              >
                <Smartphone className="inline w-4 h-4 mr-2" />
                Connect Phone
              </button>
              <div className="mt-6 p-4 rounded-lg bg-slate-800/30 border border-slate-700/30">
                <p className="text-xs text-slate-500 font-medium mb-2">
                  <span className="text-cyan-400">Quick setup:</span>
                </p>
                <ol className="text-xs text-slate-400 space-y-1 pl-4 list-decimal">
                  <li>
                    <a
                      href="/connect-phone"
                      className="text-cyan-400 hover:text-cyan-300 transition-colors"
                    >
                      Download SMS Gateway for Android
                    </a>
                  </li>
                  <li>Toggle "Local Server" to ON</li>
                  <li>Enter your phone's IP in the setup wizard</li>
                  <li>Done! Free SMS messaging</li>
                </ol>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
