'use client';

import { useState, useEffect } from 'react';
import { Phone, Eye, EyeOff, Loader2, CheckCircle2, XCircle } from 'lucide-react';
import { cn } from '@/lib/utils';

interface TwilioCardProps {
  settings: Record<string, string>;
  onSave: (updates: Record<string, string>) => Promise<void>;
  connected: boolean | null;
  onTestConnection: () => Promise<void>;
  testing: boolean;
}

function maskSid(val: string): string {
  if (!val || val.length < 8) return val ? '••••••••' : '';
  return val.slice(0, 2) + '••••••••' + val.slice(-4);
}

export default function TwilioCard({ settings, onSave, connected, onTestConnection, testing }: TwilioCardProps) {
  const [accountSid, setAccountSid] = useState('');
  const [authToken, setAuthToken] = useState('');
  const [showToken, setShowToken] = useState(false);
  const [saving, setSaving] = useState(false);
  const [editing, setEditing] = useState(false);

  // Display masked values from env/settings when not editing
  const envSid = process.env.NEXT_PUBLIC_TWILIO_SID_HINT || settings.twilio_account_sid || '';
  const envToken = settings.twilio_auth_token || '';

  async function handleSave() {
    setSaving(true);
    try {
      const updates: Record<string, string> = {};
      if (accountSid) updates.twilio_account_sid = accountSid;
      if (authToken) updates.twilio_auth_token = authToken;
      await onSave(updates);
      setEditing(false);
      setAccountSid('');
      setAuthToken('');
    } finally {
      setSaving(false);
    }
  }

  return (
    <div className="card p-6 space-y-5">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-blue-500/10 border border-blue-500/20">
            <Phone className="h-5 w-5 text-blue-400" />
          </div>
          <div>
            <h3 className="text-sm font-semibold text-white">Twilio Connection</h3>
            <p className="text-xs text-slate-500">SMS gateway credentials</p>
          </div>
        </div>
        {/* Connection status */}
        <div className="flex items-center gap-2">
          {connected === null ? (
            <span className="text-xs text-slate-500">Not tested</span>
          ) : connected ? (
            <>
              <div className="h-2.5 w-2.5 rounded-full bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.5)]" />
              <span className="text-xs font-medium text-green-400">Connected</span>
            </>
          ) : (
            <>
              <div className="h-2.5 w-2.5 rounded-full bg-red-500 shadow-[0_0_6px_rgba(239,68,68,0.5)]" />
              <span className="text-xs font-medium text-red-400">Disconnected</span>
            </>
          )}
        </div>
      </div>

      {/* Fields */}
      <div className="space-y-4">
        {/* Account SID */}
        <div>
          <label className="block text-xs font-medium text-slate-400 mb-1.5">Account SID</label>
          {editing ? (
            <input
              type="text"
              value={accountSid}
              onChange={(e) => setAccountSid(e.target.value)}
              placeholder="ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
              className="w-full rounded-lg border border-slate-700/50 bg-slate-800/50 px-3 py-2 text-sm text-slate-200 placeholder-slate-600 outline-none transition-colors focus:border-cyan-500/50 focus:ring-1 focus:ring-cyan-500/20 font-mono"
            />
          ) : (
            <div className="w-full rounded-lg border border-slate-700/30 bg-slate-800/30 px-3 py-2 text-sm text-slate-400 font-mono">
              {envSid ? maskSid(envSid) : <span className="text-slate-600 italic">Not configured</span>}
            </div>
          )}
        </div>

        {/* Auth Token */}
        <div>
          <label className="block text-xs font-medium text-slate-400 mb-1.5">Auth Token</label>
          {editing ? (
            <div className="relative">
              <input
                type={showToken ? 'text' : 'password'}
                value={authToken}
                onChange={(e) => setAuthToken(e.target.value)}
                placeholder="Your Twilio Auth Token"
                className="w-full rounded-lg border border-slate-700/50 bg-slate-800/50 px-3 py-2 pr-10 text-sm text-slate-200 placeholder-slate-600 outline-none transition-colors focus:border-cyan-500/50 focus:ring-1 focus:ring-cyan-500/20 font-mono"
              />
              <button
                type="button"
                onClick={() => setShowToken(!showToken)}
                className="absolute right-2 top-1/2 -translate-y-1/2 p-1 text-slate-500 hover:text-slate-300 transition-colors"
              >
                {showToken ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
              </button>
            </div>
          ) : (
            <div className="w-full rounded-lg border border-slate-700/30 bg-slate-800/30 px-3 py-2 text-sm text-slate-400 font-mono">
              {envToken ? '••••••••••••••••' : <span className="text-slate-600 italic">Not configured</span>}
            </div>
          )}
        </div>
      </div>

      {/* Actions */}
      <div className="flex items-center gap-3 pt-2">
        <button
          onClick={onTestConnection}
          disabled={testing}
          className="flex items-center gap-2 rounded-lg border border-slate-700/50 bg-slate-800/50 px-4 py-2 text-xs font-medium text-slate-300 transition-all hover:bg-slate-700/50 hover:text-white disabled:opacity-50"
        >
          {testing ? (
            <Loader2 className="h-3.5 w-3.5 animate-spin" />
          ) : connected ? (
            <CheckCircle2 className="h-3.5 w-3.5 text-green-400" />
          ) : (
            <XCircle className="h-3.5 w-3.5 text-slate-500" />
          )}
          Test Connection
        </button>

        {editing ? (
          <div className="flex items-center gap-2 ml-auto">
            <button
              onClick={() => { setEditing(false); setAccountSid(''); setAuthToken(''); }}
              className="rounded-lg border border-slate-700/50 px-4 py-2 text-xs font-medium text-slate-400 transition-colors hover:text-white"
            >
              Cancel
            </button>
            <button
              onClick={handleSave}
              disabled={saving || (!accountSid && !authToken)}
              className="flex items-center gap-2 rounded-lg bg-cyan-500/20 border border-cyan-500/30 px-4 py-2 text-xs font-medium text-cyan-400 transition-all hover:bg-cyan-500/30 disabled:opacity-50"
            >
              {saving && <Loader2 className="h-3.5 w-3.5 animate-spin" />}
              Save Changes
            </button>
          </div>
        ) : (
          <button
            onClick={() => setEditing(true)}
            className="ml-auto rounded-lg bg-slate-700/50 border border-slate-600/30 px-4 py-2 text-xs font-medium text-slate-300 transition-all hover:bg-slate-600/50 hover:text-white"
          >
            Edit Credentials
          </button>
        )}
      </div>
    </div>
  );
}
