import { useCallback, useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import axios from '../../../bootstrap';
import { ArrowRightLeft, Check, Eye, Plus, Trash2, X } from 'lucide-react';
import { PANEL_ROUTES } from '../../../navigation/panelRoutes';

export function KeysView() {
    const navigate = useNavigate();
    const [keys, setKeys] = useState<any[]>([]);
    const [isLoading, setIsLoading] = useState(true);
    const [showForm, setShowForm] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const [migrationRequests, setMigrationRequests] = useState<any[]>([]);
    const [migrationMessage, setMigrationMessage] = useState<string | null>(null);
    const [migrationActionId, setMigrationActionId] = useState<number | null>(null);

    // Form inputs
    const [type, setType] = useState('client');
    const [maxActivations, setMaxActivations] = useState(1);
    const [allowedDomains, setAllowedDomains] = useState('');
    const [expiresAt, setExpiresAt] = useState('');
    const [notes, setNotes] = useState('');

    const fetchKeys = async () => {
        try {
            const res = await axios.get('/activation-keys');
            setKeys(res.data.keys || []);
        } catch (err) {
            console.error(err);
        } finally {
            setIsLoading(false);
        }
    };

    const fetchMigrationRequests = useCallback(async () => {
        try {
            const res = await axios.get('/domain-migration-requests');
            setMigrationRequests(res.data.requests || []);
        } catch (err) {
            console.error(err);
        }
    }, []);

    useEffect(() => {
        fetchKeys();
        fetchMigrationRequests();
    }, [fetchMigrationRequests]);

    const handleApproveMigration = async (requestId: number, mode: 'move' | 'clone') => {
        const confirmMessage = mode === 'clone'
            ? 'Keep the old domain offline and register this as a NEW website (uses one activation slot)? Use this when one site was copied to multiple new domains.'
            : 'Move the website record to the new domain (same slot, old domain name is replaced)? Use this for a simple 1→1 domain change.';

        if (!confirm(confirmMessage)) {
            return;
        }

        setMigrationActionId(requestId);
        setMigrationMessage(null);
        try {
            const res = await axios.post(`/domain-migration-requests/${requestId}/approve`, { mode });
            setMigrationMessage(res.data.message || 'Domain migration approved.');
            await Promise.all([fetchMigrationRequests(), fetchKeys()]);
        } catch (err: any) {
            setMigrationMessage(
                err.response?.data?.message
                || err.response?.data?.errors?.new_domain?.[0]
                || err.response?.data?.errors?.activation_key?.[0]
                || 'Could not approve domain migration.'
            );
        } finally {
            setMigrationActionId(null);
        }
    };

    const handleRejectMigration = async (requestId: number) => {
        if (!confirm('Reject this domain change? Panel will keep the currently registered domain.')) {
            return;
        }

        setMigrationActionId(requestId);
        setMigrationMessage(null);
        try {
            const res = await axios.post(`/domain-migration-requests/${requestId}/reject`);
            setMigrationMessage(res.data.message || 'Domain migration rejected.');
            await fetchMigrationRequests();
        } catch (err: any) {
            setMigrationMessage(err.response?.data?.message || 'Could not reject domain migration.');
        } finally {
            setMigrationActionId(null);
        }
    };

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

        try {
            await axios.post('/activation-keys', {
                type,
                max_activations: maxActivations,
                allowed_domains: allowedDomains || null,
                expires_at: expiresAt || null,
                notes: notes || null,
            });

            // Reset form
            setType('client');
            setMaxActivations(1);
            setAllowedDomains('');
            setExpiresAt('');
            setNotes('');
            setShowForm(false);

            fetchKeys();
        } catch (err: any) {
            setError(err.response?.data?.message || 'Error generating key.');
        }
    };

    const handleDelete = async (id: number) => {
        if (!confirm('Are you sure you want to delete this activation key?')) return;
        try {
            await axios.delete(`/activation-keys/${id}`);
            fetchKeys();
        } catch (err) {
            console.error(err);
        }
    };

    const handleToggleStatus = async (keyItem: any) => {
        const nextStatus = keyItem.status === 'active' ? 'suspended' : 'active';
        try {
            await axios.put(`/activation-keys/${keyItem.id}`, {
                status: nextStatus,
                max_activations: keyItem.max_activations,
                allowed_domains: keyItem.allowed_domains,
                expires_at: keyItem.expires_at,
                notes: keyItem.notes,
            });
            fetchKeys();
        } catch (err) {
            console.error(err);
        }
    };

    if (isLoading) {
        return (
            <div className="flex justify-center items-center py-20">
                <div className="w-8 h-8 border-4 border-rose-500/20 border-t-rose-500 rounded-full animate-spin"></div>
            </div>
        );
    }

    return (
        <div className="space-y-6">
            <div className="flex justify-between items-center">
                <div>
                    <h3 className="text-xl font-bold text-white">Activation Keys</h3>
                    <p className="text-sm text-slate-400">Generate and configure keys for WordPress agent activations</p>
                </div>
                <button
                    onClick={() => setShowForm(!showForm)}
                    className="flex items-center gap-2 px-4 py-2.5 bg-rose-500 hover:bg-rose-600 text-white rounded-xl text-sm font-semibold transition-all shadow-md active:scale-95"
                >
                    <Plus className="w-4 h-4" />
                    Generate Key
                </button>
            </div>

            {/* Form Drawer / Accordion */}
            {showForm && (
                <form onSubmit={handleSubmit} className="bg-slate-900/40 border border-slate-800 rounded-2xl p-6 space-y-4 max-w-xl animate-fade-in">
                    <h4 className="text-sm font-bold uppercase tracking-wider text-slate-300">Generate New Activation Key</h4>
                    
                    {error && (
                        <div className="p-3 bg-rose-500/10 border border-rose-500/20 rounded-xl text-xs font-medium text-rose-400">
                            {error}
                        </div>
                    )}

                    <div className="grid grid-cols-2 gap-4">
                        <div className="space-y-1.5">
                            <label className="text-xs font-semibold text-slate-400 uppercase">Key Type</label>
                            <select
                                value={type}
                                onChange={(e) => setType(e.target.value)}
                                className="w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-xl text-sm text-slate-200 focus:outline-none focus:border-rose-500/40"
                            >
                                <option value="client">Client Key</option>
                                <option value="global">Global Key</option>
                            </select>
                        </div>

                        <div className="space-y-1.5">
                            <label className="text-xs font-semibold text-slate-400 uppercase">Max Activations</label>
                            <input
                                type="number"
                                min={1}
                                value={maxActivations}
                                onChange={(e) => setMaxActivations(parseInt(e.target.value))}
                                className="w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-xl text-sm text-slate-200 focus:outline-none focus:border-rose-500/40"
                            />
                        </div>
                    </div>

                    <div className="space-y-1.5">
                        <label className="text-xs font-semibold text-slate-400 uppercase">Allowed Domains (Optional, wildcard supports: *.example.com)</label>
                        <textarea
                            placeholder="example.com&#10;*.client.com"
                            value={allowedDomains}
                            onChange={(e) => setAllowedDomains(e.target.value)}
                            className="w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-xl text-sm text-slate-200 h-20 focus:outline-none focus:border-rose-500/40 font-mono text-xs"
                        />
                    </div>

                    <div className="grid grid-cols-2 gap-4">
                        <div className="space-y-1.5">
                            <label className="text-xs font-semibold text-slate-400 uppercase">Expiry Date (Optional)</label>
                            <input
                                type="date"
                                value={expiresAt}
                                onChange={(e) => setExpiresAt(e.target.value)}
                                className="w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-xl text-sm text-slate-200 focus:outline-none focus:border-rose-500/40"
                            />
                        </div>

                        <div className="space-y-1.5">
                            <label className="text-xs font-semibold text-slate-400 uppercase">Internal Notes</label>
                            <input
                                type="text"
                                placeholder="Agency portal test key"
                                value={notes}
                                onChange={(e) => setNotes(e.target.value)}
                                className="w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-xl text-sm text-slate-200 focus:outline-none focus:border-rose-500/40"
                            />
                        </div>
                    </div>

                    <div className="flex justify-end gap-3 pt-2">
                        <button
                            type="button"
                            onClick={() => setShowForm(false)}
                            className="px-4 py-2 text-xs font-semibold text-slate-400 hover:text-slate-200 border border-slate-800 rounded-xl hover:bg-slate-800/40"
                        >
                            Cancel
                        </button>
                        <button
                            type="submit"
                            className="px-4 py-2 text-xs font-semibold text-white bg-rose-500 hover:bg-rose-600 rounded-xl"
                        >
                            Generate
                        </button>
                    </div>
                </form>
            )}

            {/* Keys list */}
            <div className="bg-slate-900/40 border border-slate-800/80 rounded-2xl overflow-hidden">
                {keys.length === 0 ? (
                    <div className="text-center py-16 text-slate-500 text-sm">
                        No activation keys found. Click "Generate Key" to create your first activation token.
                    </div>
                ) : (
                    <div className="overflow-x-auto">
                        <table className="w-full text-left border-collapse">
                            <thead>
                                <tr className="border-b border-slate-800 text-xs font-semibold text-slate-400 uppercase bg-slate-900/20">
                                    <th className="py-3.5 px-4">Activation Key</th>
                                    <th className="py-3.5 px-4">Type</th>
                                    <th className="py-3.5 px-4">Quota</th>
                                    <th className="py-3.5 px-4">Status</th>
                                    <th className="py-3.5 px-4">Domains</th>
                                    <th className="py-3.5 px-4">Expires</th>
                                    <th className="py-3.5 px-4 text-right">Actions</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-slate-800/60 text-sm text-slate-300">
                                {keys.map((keyItem) => (
                                    <tr
                                        key={keyItem.id}
                                        className="hover:bg-slate-800/10 cursor-pointer"
                                        onClick={() => navigate(PANEL_ROUTES.keyDetail(keyItem.id))}
                                    >
                                        <td className="py-3.5 px-4 font-mono font-bold text-white text-xs select-all">{keyItem.key}</td>
                                        <td className="py-3.5 px-4 capitalize text-xs">
                                            <span className={`px-2 py-0.5 rounded-full text-[10px] font-semibold ${
                                                keyItem.type === 'global' ? 'bg-indigo-500/15 text-indigo-400 border border-indigo-500/20' : 'bg-slate-800 text-slate-400 border border-slate-700/40'
                                            }`}>
                                                {keyItem.type}
                                            </span>
                                        </td>
                                        <td className="py-3.5 px-4 text-xs font-semibold">
                                            {(keyItem.active_slots ?? keyItem.activations_count)} / {keyItem.max_activations}
                                        </td>
                                        <td className="py-3.5 px-4">
                                            <span className={`inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-xs font-medium ${
                                                keyItem.status === 'active' 
                                                    ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20' 
                                                    : 'bg-rose-500/10 text-rose-400 border border-rose-500/20'
                                            }`}>
                                                {keyItem.status}
                                            </span>
                                        </td>
                                        <td className="py-3.5 px-4 text-xs font-mono text-slate-400 truncate max-w-xs" title={keyItem.allowed_domains}>
                                            {keyItem.allowed_domains || 'Any'}
                                        </td>
                                        <td className="py-3.5 px-4 text-xs text-slate-500">
                                            {keyItem.expires_at 
                                                ? new Date(keyItem.expires_at).toLocaleDateString() 
                                                : 'Never'}
                                        </td>
                                        <td className="py-3.5 px-4 text-right" onClick={(e) => e.stopPropagation()}>
                                            <div className="flex justify-end gap-2.5">
                                                <button
                                                    onClick={() => navigate(PANEL_ROUTES.keyDetail(keyItem.id))}
                                                    className="p-1.5 rounded-lg border border-slate-800 text-slate-400 hover:text-white hover:bg-slate-800 transition-all"
                                                    title="View active domains"
                                                >
                                                    <Eye className="w-3.5 h-3.5" />
                                                </button>
                                                <button
                                                    onClick={() => handleToggleStatus(keyItem)}
                                                    className={`p-1.5 rounded-lg border transition-all ${
                                                        keyItem.status === 'active'
                                                            ? 'border-amber-500/20 text-amber-500/80 hover:bg-amber-500/10'
                                                            : 'border-emerald-500/20 text-emerald-400 hover:bg-emerald-500/10'
                                                    }`}
                                                    title={keyItem.status === 'active' ? 'Suspend Key' : 'Activate Key'}
                                                >
                                                    {keyItem.status === 'active' ? <X className="w-3.5 h-3.5" /> : <Check className="w-3.5 h-3.5" />}
                                                </button>
                                                <button
                                                    onClick={() => handleDelete(keyItem.id)}
                                                    className="p-1.5 rounded-lg border border-rose-500/20 text-rose-400 hover:bg-rose-500/10 hover:border-rose-500/30 transition-all"
                                                    title="Delete Key"
                                                >
                                                    <Trash2 className="w-3.5 h-3.5" />
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                )}
            </div>

            <div className="mt-8 space-y-3">
                <div className="flex items-center gap-2">
                    <ArrowRightLeft className="w-4 h-4 text-amber-400" />
                    <h2 className="text-sm font-semibold text-white">Pending domain migrations</h2>
                    {migrationRequests.length > 0 && (
                        <span className="rounded-full bg-amber-500/15 border border-amber-500/25 px-2 py-0.5 text-[10px] font-semibold text-amber-300">
                            {migrationRequests.length}
                        </span>
                    )}
                </div>
                <p className="text-xs text-slate-500">
                    When a site moves or is copied to a new domain with the same plugin credentials, choose how to approve:
                    <span className="text-slate-400"> Move</span> replaces the old domain name on the same record;
                    <span className="text-slate-400"> Keep old + add new</span> leaves the old domain offline and registers each new domain as its own website (needs a free activation slot per new domain).
                </p>
                {migrationMessage && (
                    <div className="rounded-xl border border-slate-700/60 bg-slate-900/50 px-3 py-2 text-xs text-slate-300">
                        {migrationMessage}
                    </div>
                )}
                {migrationRequests.length === 0 ? (
                    <div className="rounded-2xl border border-slate-800/80 bg-slate-900/30 px-4 py-8 text-center text-sm text-slate-500">
                        No pending domain migrations.
                    </div>
                ) : (
                    <div className="space-y-3">
                        {migrationRequests.map((item) => (
                            <div
                                key={item.id}
                                className="rounded-2xl border border-amber-500/20 bg-amber-500/[0.04] px-4 py-3.5"
                            >
                                <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                                    <div className="min-w-0 space-y-1">
                                        <div className="text-sm font-semibold text-white truncate">
                                            {item.agent?.site_name || item.old_domain}
                                        </div>
                                        <div className="flex flex-wrap items-center gap-2 text-xs font-mono text-slate-400">
                                            <span className="text-slate-500">{item.old_domain}</span>
                                            <ArrowRightLeft className="w-3 h-3 text-amber-400 shrink-0" />
                                            <span className="text-amber-300">{item.new_domain}</span>
                                        </div>
                                        <div className="text-[11px] text-slate-500">
                                            Detected {item.detected_at ? new Date(item.detected_at).toLocaleString() : '—'}
                                            {item.reported_site_url ? ` · ${item.reported_site_url}` : ''}
                                        </div>
                                    </div>
                                    <div className="flex flex-wrap gap-2 shrink-0">
                                        <button
                                            type="button"
                                            disabled={migrationActionId === item.id}
                                            onClick={() => handleApproveMigration(item.id, 'move')}
                                            className="inline-flex items-center gap-1.5 rounded-lg border border-emerald-500/30 bg-emerald-500/10 px-3 py-1.5 text-xs font-semibold text-emerald-300 hover:bg-emerald-500/20 disabled:opacity-50"
                                            title="Same website record — old domain name is replaced"
                                        >
                                            <Check className="w-3.5 h-3.5" />
                                            Move
                                        </button>
                                        <button
                                            type="button"
                                            disabled={migrationActionId === item.id}
                                            onClick={() => handleApproveMigration(item.id, 'clone')}
                                            className="inline-flex items-center gap-1.5 rounded-lg border border-sky-500/30 bg-sky-500/10 px-3 py-1.5 text-xs font-semibold text-sky-300 hover:bg-sky-500/20 disabled:opacity-50"
                                            title="Keep old offline and add new domain as a separate website"
                                        >
                                            <ArrowRightLeft className="w-3.5 h-3.5" />
                                            Keep old + add new
                                        </button>
                                        <button
                                            type="button"
                                            disabled={migrationActionId === item.id}
                                            onClick={() => handleRejectMigration(item.id)}
                                            className="inline-flex items-center gap-1.5 rounded-lg border border-rose-500/30 bg-rose-500/10 px-3 py-1.5 text-xs font-semibold text-rose-300 hover:bg-rose-500/20 disabled:opacity-50"
                                        >
                                            <X className="w-3.5 h-3.5" />
                                            Reject
                                        </button>
                                    </div>
                                </div>
                            </div>
                        ))}
                    </div>
                )}
            </div>
        </div>
    );
}
