
import React, { useState } from 'react';
import { 
  ArrowLeft, Shield, Key, Globe, RefreshCcw, 
  Lock, Unlock, Copy, Save, ExternalLink, 
  Server, Calendar, DollarSign, Clock 
} from 'lucide-react';
import { Domain, DashboardView, ClientStats } from '../types';
import { callWHMCS } from '../services/whmcsService';

interface DomainDetailProps {
  domain: Domain;
  stats: ClientStats | null;
  onBack: () => void;
}

const DomainDetailView: React.FC<DomainDetailProps> = ({ domain, stats, onBack }) => {
  const [ns, setNs] = useState(domain.nameservers);
  const [saving, setSaving] = useState(false);
  const [registrarLock, setRegistrarLock] = useState(domain.registrarLock);
  const [showAuthCode, setShowAuthCode] = useState(false);

  const updateNameservers = async () => {
    setSaving(true);
    await callWHMCS('DomainUpdateNameservers', { domainid: domain.id, ns1: ns[0], ns2: ns[1] });
    setSaving(false);
    alert('Nameservers updated successfully!');
  };

  const toggleLock = async () => {
    setRegistrarLock(!registrarLock);
    await callWHMCS('DomainUpdateLockingStatus', { domainid: domain.id, lockstatus: !registrarLock });
  };

  return (
    <div className="space-y-8 pb-12 animate-in fade-in duration-300">
      <div className="flex items-center gap-4">
        <button 
          onClick={onBack}
          className="p-2 hover:bg-white rounded-xl transition-colors border border-transparent hover:border-slate-200"
        >
          <ArrowLeft size={20} />
        </button>
        <div>
          <h1 className="text-2xl font-bold text-slate-900">{domain.domain}</h1>
          <p className="text-sm text-slate-500 flex items-center gap-1.5">
            <span className="w-2 h-2 rounded-full bg-emerald-500"></span>
            Managed Domain Detail
          </p>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
        {[
          { icon: Calendar, label: "Registered", value: domain.regDate },
          { icon: Clock, label: "Expires", value: domain.expiryDate },
          { icon: DollarSign, label: "Renewal", value: `${stats?.currencyPrefix ?? '৳'}${domain.recurringAmount.toFixed(2)}${stats?.currencySuffix ?? ''}` },
          { icon: Shield, label: "Status", value: domain.status, color: 'text-emerald-600' }
        ].map((stat, i) => (
          <div key={i} className="bg-white p-5 rounded-2xl border border-slate-100 shadow-sm">
            <div className="flex items-center gap-3 mb-2 text-slate-400">
              <stat.icon size={16} />
              <span className="text-[10px] font-bold uppercase tracking-widest">{stat.label}</span>
            </div>
            <p className={`font-bold ${stat.color || 'text-slate-900'}`}>{stat.value}</p>
          </div>
        ))}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
        {/* Nameservers Section */}
        <div className="bg-white rounded-3xl border border-slate-100 shadow-sm overflow-hidden">
          <div className="p-6 border-b border-slate-50 flex items-center justify-between bg-slate-50/50">
            <div className="flex items-center gap-3">
              <Server className="text-blue-600" size={20} />
              <h3 className="font-bold text-slate-900">Nameservers</h3>
            </div>
            <button 
              disabled={saving}
              onClick={updateNameservers}
              className="px-4 py-2 bg-blue-600 text-white rounded-xl text-xs font-bold hover:bg-blue-700 disabled:opacity-50 transition-all flex items-center gap-2"
            >
              {saving ? <RefreshCcw size={14} className="animate-spin" /> : <Save size={14} />}
              Save Changes
            </button>
          </div>
          <div className="p-6 space-y-4">
            {ns.map((n, i) => (
              <div key={i}>
                <label className="text-[10px] font-black uppercase text-slate-400 mb-1.5 block tracking-widest">Nameserver {i + 1}</label>
                <input 
                  type="text" 
                  value={n}
                  onChange={(e) => {
                    const newNs = [...ns];
                    newNs[i] = e.target.value;
                    setNs(newNs);
                  }}
                  className="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent outline-none"
                />
              </div>
            ))}
            <div className="p-4 bg-amber-50 rounded-2xl border border-amber-100 mt-4">
                <p className="text-[11px] text-amber-700 font-medium leading-relaxed">Changes to nameservers can take up to 24-48 hours to propagate globally.</p>
            </div>
          </div>
        </div>

        {/* Security & Management */}
        <div className="space-y-6">
          <div className="bg-white rounded-3xl border border-slate-100 shadow-sm p-6">
            <h3 className="font-bold text-slate-900 mb-6 flex items-center gap-3">
              <Lock className="text-indigo-600" size={20} />
              Registrar Lock
            </h3>
            <div className="flex items-center justify-between p-4 bg-slate-50 rounded-2xl border border-slate-200">
              <div>
                <p className="text-sm font-bold text-slate-900">{registrarLock ? 'Lock Enabled' : 'Lock Disabled'}</p>
                <p className="text-xs text-slate-500 mt-1">Prevents unauthorized transfers.</p>
              </div>
              <button 
                onClick={toggleLock}
                className={`p-3 rounded-xl transition-all ${registrarLock ? 'bg-emerald-600 text-white shadow-lg shadow-emerald-500/20' : 'bg-slate-200 text-slate-600'}`}
              >
                {registrarLock ? <Lock size={20} /> : <Unlock size={20} />}
              </button>
            </div>
          </div>

          <div className="bg-white rounded-3xl border border-slate-100 shadow-sm p-6">
            <h3 className="font-bold text-slate-900 mb-6 flex items-center gap-3">
              <Key className="text-amber-600" size={20} />
              Transfer Authorization
            </h3>
            <div className="space-y-4">
                <button 
                  onClick={() => setShowAuthCode(!showAuthCode)}
                  className="w-full py-4 bg-slate-900 text-white rounded-2xl font-bold text-sm hover:bg-slate-800 transition-all flex items-center justify-center gap-3"
                >
                  {showAuthCode ? <RefreshCcw size={18} /> : <Copy size={18} />}
                  {showAuthCode ? 'Hide EPP / Auth Code' : 'Get EPP / Auth Code'}
                </button>
                {showAuthCode && (
                  <div className="p-4 bg-slate-100 rounded-2xl border-2 border-dashed border-slate-300 animate-in zoom-in-95 duration-200">
                    <p className="text-center font-mono font-black text-xl text-slate-800 tracking-wider">
                      {domain.authCode || 'NO-AUTH-CODE'}
                    </p>
                    <p className="text-center text-[10px] text-slate-400 mt-2 font-bold uppercase tracking-widest">Valid for 24 hours</p>
                  </div>
                )}
            </div>
          </div>
          
          <div className="bg-gradient-to-br from-slate-900 to-slate-800 rounded-3xl p-6 text-white">
              <h3 className="font-bold mb-4 flex items-center gap-2">
                  <Globe size={18} className="text-blue-400" />
                  Management Actions
              </h3>
              <div className="grid grid-cols-2 gap-3">
                  {['Child NS', 'DNS Records', 'ID Protection', 'Contact Info'].map(label => (
                      <button key={label} className="p-3 bg-white/5 border border-white/10 rounded-xl text-xs font-bold hover:bg-white/10 transition-all">
                          {label}
                      </button>
                  ))}
              </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default DomainDetailView;
