'use client';

import React, { useState } from 'react';
import {
  Key,
  Plus,
  ShieldCheck,
  Search,
  Globe,
  Edit2,
  Trash2,
  Copy,
  Check,
  X,
  Save,
  RefreshCw,
  Zap,
  Calendar,
  AlertCircle,
} from 'lucide-react';
import { License, Product, User, BillingCycle } from '@/types';
import AdminSidebar from '@/components/admin/AdminSidebar';

interface AdminLicensesClientProps {
  initialLicenses: License[];
  products: Product[];
  users: User[];
}

export default function AdminLicensesClient({
  initialLicenses,
  products,
  users,
}: AdminLicensesClientProps) {
  const [licenses, setLicenses] = useState<License[]>(initialLicenses);
  const [search, setSearch] = useState('');
  const [copiedKey, setCopiedKey] = useState<string | null>(null);

  // Generate / Edit Modal
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingLic, setEditingLic] = useState<License | null>(null);
  const [selectedProductId, setSelectedProductId] = useState<string>(products[0]?.id ? String(products[0].id) : '');
  const [selectedUserId, setSelectedUserId] = useState<string>(users[0]?.id || 'usr-demo');
  const [planType, setPlanType] = useState<BillingCycle>('semiannual');
  const [boundDomain, setBoundDomain] = useState('');
  const [boundIp, setBoundIp] = useState('');
  const [status, setStatus] = useState<License['status']>('active');
  const [customExpiry, setCustomExpiry] = useState<string>('');

  // Live Remote API Verifier State
  const [testKey, setTestKey] = useState('');
  const [testDomain, setTestDomain] = useState('');
  const [testIp, setTestIp] = useState('');
  const [testResult, setTestResult] = useState<any>(null);
  const [isTesting, setIsTesting] = useState(false);

  const copyToClipboard = (text: string, id: string) => {
    navigator.clipboard.writeText(text);
    setCopiedKey(id);
    setTimeout(() => setCopiedKey(null), 2500);
  };

  const openGenerateModal = () => {
    setEditingLic(null);
    setSelectedProductId(products[0]?.id ? String(products[0].id) : '');
    setSelectedUserId(users[0]?.id || 'usr-demo');
    setPlanType('semiannual');
    setBoundDomain('');
    setBoundIp('');
    setStatus('active');
    setCustomExpiry('');
    setIsModalOpen(true);
  };

  const openEditModal = (lic: License) => {
    setEditingLic(lic);
    setSelectedProductId(String(lic.product_id));
    setSelectedUserId(lic.user_id);
    setPlanType(lic.plan_type);
    setBoundDomain(lic.bound_domain || '');
    setBoundIp(lic.bound_ip || '');
    setStatus(lic.status);
    setCustomExpiry(lic.expires_at ? lic.expires_at.split('T')[0] : '');
    setIsModalOpen(true);
  };

  const handleSaveLicense = async (e: React.FormEvent) => {
    e.preventDefault();
    const prod = products.find((p) => String(p.id) === String(selectedProductId));

    let calculatedExpiry: string | null = null;
    if (customExpiry) {
      calculatedExpiry = new Date(customExpiry).toISOString();
    } else if (planType === 'monthly') {
      calculatedExpiry = new Date(Date.now() + 30 * 86400000).toISOString();
    } else if (planType === 'semiannual') {
      calculatedExpiry = new Date(Date.now() + 180 * 86400000).toISOString();
    } else if (planType === 'yearly') {
      calculatedExpiry = new Date(Date.now() + 365 * 86400000).toISOString();
    } else if (planType === 'trial') {
      calculatedExpiry = new Date(Date.now() + 3 * 86400000).toISOString();
    }

    if (editingLic) {
      try {
        const res = await fetch('/api/licenses', {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            license_key: editingLic.license_key,
            bound_domain: boundDomain.trim(),
            bound_ip: boundIp.trim(),
            status,
            expires_at: calculatedExpiry,
            plan_type: planType,
          }),
        });
        const data = await res.json();
        if (data.license) {
          setLicenses(licenses.map((l) => (l.id === editingLic.id ? { ...data.license, status, plan_type: planType, expires_at: calculatedExpiry } : l)));
        }
      } catch {
        setLicenses(
          licenses.map((l) =>
            l.id === editingLic.id
              ? { ...l, bound_domain: boundDomain, bound_ip: boundIp, status, plan_type: planType, expires_at: calculatedExpiry }
              : l
          )
        );
      }
    } else {
      // Create new license
      const seg = () => Math.random().toString(36).substring(2, 6).toUpperCase();
      const newKey = `TZ-${seg()}-${seg()}-${seg()}-${seg()}`;
      const newLic: License = {
        id: `lic-${Date.now()}`,
        order_id: `ord-manual-${Date.now()}`,
        user_id: selectedUserId,
        product_id: Number(selectedProductId),
        product_title: prod?.title || 'Manual Generated Product',
        product_slug: prod?.slug || 'manual-license',
        license_key: newKey,
        plan_type: planType,
        bound_domain: boundDomain.trim() || undefined,
        bound_ip: boundIp.trim() || undefined,
        status: status,
        expires_at: calculatedExpiry,
        created_at: new Date().toISOString(),
      };
      setLicenses([newLic, ...licenses]);
    }
    setIsModalOpen(false);
  };

  const handleRegenerateKey = (lic: License) => {
    if (!confirm('Are you sure you want to regenerate this license key? The old key will become invalid.')) return;
    const seg = () => Math.random().toString(36).substring(2, 6).toUpperCase();
    const newKey = `TZ-${seg()}-${seg()}-${seg()}-${seg()}`;
    setLicenses(licenses.map((l) => (l.id === lic.id ? { ...l, license_key: newKey } : l)));
  };

  const handleDeleteLicense = (licId: string) => {
    if (!confirm('Are you sure you want to delete this license permanently?')) return;
    setLicenses(licenses.filter((l) => l.id !== licId));
  };

  const handleTestRemoteVerification = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!testKey.trim()) return;
    setIsTesting(true);
    setTestResult(null);

    try {
      const res = await fetch('/api/v1/license/verify', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          license_key: testKey.trim(),
          domain: testDomain.trim() || undefined,
          ip: testIp.trim() || undefined,
        }),
      });
      const data = await res.json();
      setTestResult(data);
    } catch (err: any) {
      setTestResult({ valid: false, message: err.message || 'Verification call failed' });
    } finally {
      setIsTesting(false);
    }
  };

  const filteredLicenses = licenses.filter((l) => {
    if (search.trim()) {
      const q = search.toLowerCase();
      const matchKey = l.license_key.toLowerCase().includes(q);
      const matchTitle = l.product_title.toLowerCase().includes(q);
      const matchDomain = l.bound_domain?.toLowerCase().includes(q);
      if (!matchKey && !matchTitle && !matchDomain) return false;
    }
    return true;
  });

  return (
    <div className="py-8 md:py-12 bg-gray-50 min-h-screen">
      <div className="container mx-auto px-4 max-w-7xl">
        <div className="flex flex-col lg:flex-row gap-8 items-start">
          <AdminSidebar />

          <div className="flex-1 space-y-6 w-full">
            {/* Header */}
            <div className="bg-white rounded-3xl p-6 sm:p-8 shadow-sm border border-gray-100 flex flex-col sm:flex-row sm:items-center justify-between gap-4">
              <div>
                <h1 className="text-2xl sm:text-3xl font-black text-gray-900 flex items-center gap-2">
                  <ShieldCheck className="w-8 h-8 text-indigo-600" />
                  <span>License Management & Remote API ({licenses.length})</span>
                </h1>
                <p className="text-xs sm:text-sm text-gray-500 mt-1">
                  Issue multi-tier subscription keys (Monthly, 6-Month, 1-Year, Lifetime), whitelist domains/IPs, and test remote handshake.
                </p>
              </div>

              <button
                onClick={openGenerateModal}
                className="px-6 py-3 bg-indigo-600 hover:bg-indigo-700 text-white font-bold text-xs rounded-xl shadow-md transition flex items-center justify-center gap-2 shrink-0 active:scale-95"
              >
                <Plus className="w-4 h-4" />
                <span>Issue License Key</span>
              </button>
            </div>

            {/* Remote License Verification Simulator */}
            <div className="bg-gradient-to-r from-gray-900 to-indigo-950 rounded-3xl p-6 text-white space-y-4 shadow-lg border border-indigo-800/40">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <Zap className="w-5 h-5 text-amber-400" />
                  <h3 className="font-extrabold text-sm text-white">
                    Live Remote Verification API Tester (/api/v1/license/verify)
                  </h3>
                </div>
                <span className="text-[10px] font-mono uppercase bg-white/10 px-2.5 py-1 rounded-full text-indigo-200">
                  v1.0 Endpoint Ready
                </span>
              </div>

              <form onSubmit={handleTestRemoteVerification} className="grid grid-cols-1 sm:grid-cols-4 gap-3 text-xs">
                <div>
                  <input
                    type="text"
                    placeholder="License Key"
                    value={testKey}
                    onChange={(e) => setTestKey(e.target.value)}
                    className="w-full py-2.5 px-3 bg-white/10 border border-white/20 rounded-xl font-mono text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-amber-400"
                  />
                </div>
                <div>
                  <input
                    type="text"
                    placeholder="Domain (e.g. client.com)"
                    value={testDomain}
                    onChange={(e) => setTestDomain(e.target.value)}
                    className="w-full py-2.5 px-3 bg-white/10 border border-white/20 rounded-xl font-mono text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-amber-400"
                  />
                </div>
                <div>
                  <input
                    type="text"
                    placeholder="Server IP (Optional)"
                    value={testIp}
                    onChange={(e) => setTestIp(e.target.value)}
                    className="w-full py-2.5 px-3 bg-white/10 border border-white/20 rounded-xl font-mono text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-amber-400"
                  />
                </div>
                <div>
                  <button
                    type="submit"
                    disabled={isTesting || !testKey.trim()}
                    className="w-full py-2.5 bg-amber-400 hover:bg-amber-300 text-gray-950 font-black rounded-xl transition disabled:opacity-50 flex items-center justify-center gap-1.5"
                  >
                    {isTesting ? 'Checking...' : 'Verify Key'}
                  </button>
                </div>
              </form>

              {testResult && (
                <div
                  className={`p-3.5 rounded-2xl text-xs font-mono border ${
                    testResult.valid
                      ? 'bg-emerald-950/80 border-emerald-500/50 text-emerald-300'
                      : 'bg-red-950/80 border-red-500/50 text-red-300'
                  }`}
                >
                  <div className="flex items-center gap-2 font-bold mb-1">
                    <span>{testResult.valid ? '✅ VALID & ACTIVE' : '❌ INVALID / RESTRICTED'}</span>
                    <span className="text-[10px] text-gray-400">({testResult.status || 'unknown'})</span>
                  </div>
                  <div>{testResult.message}</div>
                  {testResult.expires_at && (
                    <div className="text-[11px] text-gray-300 mt-1">
                      Expires: {new Date(testResult.expires_at).toLocaleString()}
                    </div>
                  )}
                </div>
              )}
            </div>

            {/* Search */}
            <div className="bg-white rounded-2xl p-4 sm:p-5 shadow-sm border border-gray-100 flex items-center justify-between">
              <div className="relative w-full sm:w-80">
                <input
                  type="text"
                  placeholder="Search key, bound domain, product..."
                  value={search}
                  onChange={(e) => setSearch(e.target.value)}
                  className="w-full text-xs py-2 pl-9 pr-3 bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:ring-2 focus:ring-indigo-600 font-mono"
                />
                <Search className="w-4 h-4 text-gray-400 absolute left-3 top-1/2 -translate-y-1/2" />
              </div>
            </div>

            {/* Licenses Table */}
            <div className="bg-white rounded-3xl shadow-sm border border-gray-100 overflow-hidden">
              <div className="overflow-x-auto">
                <table className="w-full text-left text-xs">
                  <thead className="bg-gray-50/80 text-gray-400 font-bold uppercase tracking-wider border-b border-gray-100">
                    <tr>
                      <th className="px-6 py-4">License Key</th>
                      <th className="px-4 py-4">Product</th>
                      <th className="px-4 py-4">Bound Domain / IP</th>
                      <th className="px-4 py-4">Plan Duration</th>
                      <th className="px-4 py-4">Status</th>
                      <th className="px-4 py-4">Expires</th>
                      <th className="px-6 py-4 text-right">Actions</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-100 text-gray-700">
                    {filteredLicenses.map((lic) => (
                      <tr key={lic.id} className="hover:bg-gray-50/50 transition">
                        <td className="px-6 py-4">
                          <div className="flex items-center gap-2">
                            <span className="font-mono font-bold text-sm text-indigo-700 select-all">
                              {lic.license_key}
                            </span>
                            <button
                              type="button"
                              onClick={() => copyToClipboard(lic.license_key, lic.id)}
                              className="p-1 hover:bg-gray-100 rounded text-gray-400 hover:text-indigo-600"
                            >
                              {copiedKey === lic.id ? (
                                <Check className="w-3.5 h-3.5 text-emerald-600" />
                              ) : (
                                <Copy className="w-3.5 h-3.5" />
                              )}
                            </button>
                          </div>
                          <span className="text-[11px] text-gray-400 block mt-0.5">
                            Created: {new Date(lic.created_at).toLocaleDateString()}
                          </span>
                        </td>

                        <td className="px-4 py-4">
                          <strong className="text-gray-900 font-bold block max-w-xs truncate">
                            {lic.product_title}
                          </strong>
                        </td>

                        <td className="px-4 py-4">
                          {lic.bound_domain ? (
                            <div className="space-y-0.5">
                              <span className="font-mono font-bold text-gray-800 flex items-center gap-1">
                                <Globe className="w-3 h-3 text-indigo-600" />
                                {lic.bound_domain}
                              </span>
                              {lic.bound_ip && (
                                <span className="text-[10px] text-gray-400 font-mono block">
                                  IP: {lic.bound_ip}
                                </span>
                              )}
                            </div>
                          ) : (
                            <span className="text-gray-400 italic">Unbound / Auto-bind</span>
                          )}
                        </td>

                        <td className="px-4 py-4">
                          <span className="text-[10px] font-extrabold uppercase px-2 py-0.5 rounded bg-gray-100 text-gray-700">
                            {lic.plan_type === 'semiannual' ? '6 Months' : lic.plan_type}
                          </span>
                        </td>

                        <td className="px-4 py-4">
                          <span
                            className={`font-bold text-xs uppercase px-2.5 py-0.5 rounded-full ${
                              lic.status === 'active'
                                ? 'bg-emerald-100 text-emerald-700'
                                : lic.status === 'trial'
                                ? 'bg-blue-100 text-blue-700'
                                : lic.status === 'expired'
                                ? 'bg-red-100 text-red-700'
                                : 'bg-amber-100 text-amber-700'
                            }`}
                          >
                            {lic.status}
                          </span>
                        </td>

                        <td className="px-4 py-4 font-mono text-[11px] text-gray-600">
                          {lic.expires_at
                            ? new Date(lic.expires_at).toLocaleDateString()
                            : 'Lifetime'}
                        </td>

                        <td className="px-6 py-4 text-right">
                          <div className="flex items-center justify-end gap-1">
                            <button
                              onClick={() => {
                                setTestKey(lic.license_key);
                                setTestDomain(lic.bound_domain || 'example.com');
                              }}
                              className="p-1.5 text-gray-400 hover:text-amber-600 hover:bg-amber-50 rounded-lg transition"
                              title="Test Remote API"
                            >
                              <Zap className="w-3.5 h-3.5" />
                            </button>
                            <button
                              onClick={() => handleRegenerateKey(lic)}
                              className="p-1.5 text-gray-400 hover:text-indigo-600 hover:bg-indigo-50 rounded-lg transition"
                              title="Regenerate Key"
                            >
                              <RefreshCw className="w-3.5 h-3.5" />
                            </button>
                            <button
                              onClick={() => openEditModal(lic)}
                              className="p-1.5 text-gray-400 hover:text-indigo-600 hover:bg-indigo-50 rounded-lg transition"
                              title="Edit Domain & Status"
                            >
                              <Edit2 className="w-3.5 h-3.5" />
                            </button>
                            <button
                              onClick={() => handleDeleteLicense(lic.id)}
                              className="p-1.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition"
                              title="Delete License"
                            >
                              <Trash2 className="w-3.5 h-3.5" />
                            </button>
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Generate / Edit License Modal */}
      {isModalOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
          <div className="fixed inset-0 bg-black/60 backdrop-blur-sm" onClick={() => setIsModalOpen(false)} />
          <div className="relative w-full max-w-lg bg-white rounded-3xl shadow-2xl p-6 sm:p-8 space-y-5 z-10 animate-fade-in">
            <div className="flex items-center justify-between border-b border-gray-100 pb-3">
              <h3 className="text-xl font-black text-gray-900">
                {editingLic ? 'Configure License & Expiry' : 'Issue New Software License'}
              </h3>
              <button
                onClick={() => setIsModalOpen(false)}
                className="w-8 h-8 rounded-full bg-gray-100 hover:bg-gray-200 text-gray-500 flex items-center justify-center"
              >
                <X className="w-4 h-4" />
              </button>
            </div>

            <form onSubmit={handleSaveLicense} className="space-y-4 text-xs">
              {!editingLic && (
                <div>
                  <label className="block font-bold text-gray-700 mb-1">Target Product *</label>
                  <select
                    value={selectedProductId}
                    onChange={(e) => setSelectedProductId(e.target.value)}
                    className="w-full py-2.5 px-3 bg-gray-50 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-indigo-600 font-semibold"
                  >
                    {products.map((p) => (
                      <option key={p.id} value={p.id}>
                        {p.title}
                      </option>
                    ))}
                  </select>
                </div>
              )}

              <div>
                <label className="block font-bold text-gray-700 mb-1">Subscription Billing Period</label>
                <select
                  value={planType}
                  onChange={(e) => setPlanType(e.target.value as any)}
                  className="w-full py-2.5 px-3 bg-gray-50 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-indigo-600 font-semibold"
                >
                  <option value="trial">3-Day Free Trial</option>
                  <option value="monthly">1 Month (30 Days)</option>
                  <option value="semiannual">6 Months (180 Days)</option>
                  <option value="yearly">1 Year (365 Days)</option>
                  <option value="lifetime">Lifetime License</option>
                </select>
              </div>

              <div>
                <label className="block font-bold text-gray-700 mb-1">
                  Custom Expiration Date (Overrides interval):
                </label>
                <input
                  type="date"
                  value={customExpiry}
                  onChange={(e) => setCustomExpiry(e.target.value)}
                  className="w-full py-2.5 px-3 bg-gray-50 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-indigo-600 font-mono"
                />
              </div>

              <div>
                <label className="block font-bold text-gray-700 mb-1">Authorized Bound Domain</label>
                <input
                  type="text"
                  placeholder="e.g. billing.hostneko.com"
                  value={boundDomain}
                  onChange={(e) => setBoundDomain(e.target.value)}
                  className="w-full py-2.5 px-3 bg-gray-50 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-indigo-600 font-mono"
                />
              </div>

              <div>
                <label className="block font-bold text-gray-700 mb-1">Bound Server IP (Optional)</label>
                <input
                  type="text"
                  placeholder="e.g. 192.0.2.1"
                  value={boundIp}
                  onChange={(e) => setBoundIp(e.target.value)}
                  className="w-full py-2.5 px-3 bg-gray-50 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-indigo-600 font-mono"
                />
              </div>

              <div>
                <label className="block font-bold text-gray-700 mb-1">License Status</label>
                <select
                  value={status}
                  onChange={(e) => setStatus(e.target.value as any)}
                  className="w-full py-2.5 px-3 bg-gray-50 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-indigo-600 font-semibold"
                >
                  <option value="active">Active (Verified & Allowed)</option>
                  <option value="trial">Trial Mode</option>
                  <option value="suspended">Suspended / Revoked</option>
                  <option value="expired">Expired (Requires Renewal)</option>
                </select>
              </div>

              <div className="flex justify-end gap-3 pt-3 border-t border-gray-100">
                <button
                  type="button"
                  onClick={() => setIsModalOpen(false)}
                  className="px-5 py-2.5 bg-gray-100 hover:bg-gray-200 text-gray-700 font-semibold rounded-xl"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="px-6 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white font-bold rounded-xl shadow-md transition flex items-center gap-1.5"
                >
                  <Save className="w-4 h-4" />
                  <span>Save License</span>
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
