import React, { useEffect, useState } from 'react';
import axios from '../../../bootstrap';
import { Plus, Trash2, Edit3, Star, Globe2, Send, ShieldCheck, Loader2, AlertTriangle } from 'lucide-react';

function formatTimestamp(value: string | null | undefined): string {
    if (!value) return 'Never';
    return new Date(value).toLocaleString();
}

function ConnectionBadge({ status }: { status: string }) {
    const styles: Record<string, string> = {
        verified: 'bg-emerald-500/10 text-emerald-400 border-emerald-500/20',
        failed: 'bg-rose-500/10 text-rose-400 border-rose-500/20',
        unknown: 'bg-slate-800 text-slate-400 border-slate-700/50',
    };
    const labels: Record<string, string> = {
        verified: '✓ Verified',
        failed: '✗ Failed',
        unknown: '⚠ Unverified',
    };

    return (
        <span className={`inline-flex rounded-md border px-2 py-0.5 text-[10px] font-bold uppercase ${styles[status] || styles.unknown}`}>
            {labels[status] || 'Not Configured'}
        </span>
    );
}

export function TelegramView() {
    const [profiles, setProfiles] = useState<any[]>([]);
    const [agents, setAgents] = useState<any[]>([]);
    const [isLoading, setIsLoading] = useState(true);
    const [showForm, setShowForm] = useState(false);
    const [editingId, setEditingId] = useState<number | null>(null);
    const [error, setError] = useState<string | null>(null);

    // Form inputs
    const [name, setName] = useState('');
    const [botToken, setBotToken] = useState('');
    const [chatId, setChatId] = useState('');
    const [isDefault, setIsDefault] = useState(false);
    const [assignedAgentIds, setAssignedAgentIds] = useState<string[]>([]);
    const [actionLoading, setActionLoading] = useState<Record<number, 'test' | 'verify' | null>>({});
    const [actionMessage, setActionMessage] = useState<string | null>(null);

    const fetchData = async () => {
        try {
            const [profilesRes, agentsRes] = await Promise.all([
                axios.get('/telegram-profiles'),
                axios.get('/agents'),
            ]);
            setProfiles(profilesRes.data.profiles || []);
            setAgents(agentsRes.data.agents || []);
        } catch (err) {
            console.error(err);
        } finally {
            setIsLoading(false);
        }
    };

    useEffect(() => {
        fetchData();
    }, []);

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

        if (!name || !botToken || !chatId) {
            setError('All fields are required.');
            return;
        }

        try {
            if (editingId) {
                await axios.put(`/telegram-profiles/${editingId}`, {
                    name,
                    bot_token: botToken,
                    chat_id: chatId,
                    is_default: isDefault,
                    assigned_agent_ids: isDefault ? [] : assignedAgentIds,
                });
            } else {
                await axios.post('/telegram-profiles', {
                    name,
                    bot_token: botToken,
                    chat_id: chatId,
                    is_default: isDefault,
                    assigned_agent_ids: isDefault ? [] : assignedAgentIds,
                });
            }

            // Reset form
            setName('');
            setBotToken('');
            setChatId('');
            setIsDefault(false);
            setAssignedAgentIds([]);
            setShowForm(false);
            setEditingId(null);

            fetchData();
        } catch (err: any) {
            setError(err.response?.data?.message || 'Error saving profile.');
        }
    };

    const handleEdit = (profile: any) => {
        setName(profile.name);
        setBotToken(profile.bot_token);
        setChatId(profile.chat_id);
        setIsDefault(Boolean(profile.is_default));
        setAssignedAgentIds((profile.agents || []).map((agent: any) => agent.id));
        setEditingId(profile.id);
        setShowForm(true);
    };

    const handleDelete = async (id: number) => {
        if (!confirm('Are you sure you want to delete this Telegram Profile? Websites using it will fallback to Global telegram settings.')) return;
        try {
            await axios.delete(`/telegram-profiles/${id}`);
            fetchData();
        } catch (err) {
            console.error(err);
        }
    };

    const handleCancel = () => {
        setName('');
        setBotToken('');
        setChatId('');
        setIsDefault(false);
        setAssignedAgentIds([]);
        setShowForm(false);
        setEditingId(null);
        setError(null);
    };

    const handleAgentAssignmentChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
        setAssignedAgentIds(Array.from(e.target.selectedOptions).map((option) => option.value));
    };

    const handleSendTest = async (id: number) => {
        setActionMessage(null);
        setActionLoading((prev) => ({ ...prev, [id]: 'test' }));
        try {
            const res = await axios.post(`/telegram-profiles/${id}/test`);
            setActionMessage(res.data.message || 'Test notification sent.');
            fetchData();
        } catch (err: any) {
            setActionMessage(err.response?.data?.message || 'Test notification failed.');
        } finally {
            setActionLoading((prev) => ({ ...prev, [id]: null }));
        }
    };

    const handleVerify = async (id: number) => {
        setActionMessage(null);
        setActionLoading((prev) => ({ ...prev, [id]: 'verify' }));
        try {
            const res = await axios.post(`/telegram-profiles/${id}/verify`);
            setActionMessage(res.data.message || 'Bot verified successfully.');
            fetchData();
        } catch (err: any) {
            setActionMessage(err.response?.data?.message || 'Bot verification failed.');
        } finally {
            setActionLoading((prev) => ({ ...prev, [id]: null }));
        }
    };

    const hasDefaultProfile = profiles.some((p) => p.is_default);

    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">Telegram Notification Profiles</h3>
                    <p className="text-sm text-slate-400">Configure multiple Telegram bots to route security alerts</p>
                </div>
                <button
                    onClick={() => { setShowForm(!showForm); setEditingId(null); setIsDefault(false); setAssignedAgentIds([]); }}
                    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" />
                    New Profile
                </button>
            </div>

            {!hasDefaultProfile && (
                <div className="flex items-start gap-3 p-4 bg-amber-500/10 border border-amber-500/30 rounded-2xl">
                    <AlertTriangle className="w-5 h-5 text-amber-400 shrink-0 mt-0.5" />
                    <div>
                        <p className="text-sm font-bold text-amber-300">Not Configured</p>
                        <p className="text-xs text-amber-200/70 mt-1">
                            No Default Telegram Profile is set. Security alerts will fail until you create a profile and mark it as the global default.
                        </p>
                    </div>
                </div>
            )}

            {actionMessage && (
                <div className="p-3 bg-slate-900/60 border border-slate-800 rounded-xl text-xs text-slate-300">
                    {actionMessage}
                </div>
            )}

            {/* Form Drawer */}
            {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">
                        {editingId ? 'Edit Telegram Profile' : 'Create New Telegram Profile'}
                    </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="space-y-1.5">
                        <label className="text-xs font-semibold text-slate-400 uppercase">Profile Name</label>
                        <input
                            type="text"
                            placeholder="Agency VIP, Backup hosting, etc."
                            value={name}
                            onChange={(e) => setName(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">Bot Token</label>
                        <input
                            type="text"
                            placeholder="1234567890:ABCdefGhIJKlmNoPQRsTUVwxyZ"
                            value={botToken}
                            onChange={(e) => setBotToken(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 font-mono text-xs"
                        />
                    </div>

                    <div className="space-y-1.5">
                        <label className="text-xs font-semibold text-slate-400 uppercase">Chat ID</label>
                        <input
                            type="text"
                            placeholder="-100123456789"
                            value={chatId}
                            onChange={(e) => setChatId(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 font-mono text-xs"
                        />
                    </div>

                    <div className="space-y-3 rounded-xl border border-slate-800 bg-slate-950/50 p-4">
                        <label className="flex items-center justify-between gap-4">
                            <span className="flex items-center gap-2">
                                <Star className="h-4 w-4 text-amber-400" />
                                <span>
                                    <span className="block text-xs font-semibold uppercase text-slate-300">Default Global Profile</span>
                                    <span className="block text-[11px] text-slate-500">Used when a website has no specific Telegram profile.</span>
                                </span>
                            </span>
                            <input
                                type="checkbox"
                                checked={isDefault}
                                onChange={(e) => setIsDefault(e.target.checked)}
                                className="h-4 w-4 accent-rose-500"
                            />
                        </label>

                        {!isDefault && (
                            <div className="space-y-1.5">
                                <label className="text-xs font-semibold text-slate-400 uppercase">Specific Websites</label>
                                <select
                                    multiple
                                    value={assignedAgentIds}
                                    onChange={handleAgentAssignmentChange}
                                    className="h-28 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"
                                >
                                    {agents.map((agent) => (
                                        <option key={agent.id} value={agent.id}>
                                            {agent.site_name} ({agent.domain})
                                        </option>
                                    ))}
                                </select>
                            </div>
                        )}
                    </div>

                    <div className="flex justify-end gap-3 pt-2">
                        <button
                            type="button"
                            onClick={handleCancel}
                            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"
                        >
                            {editingId ? 'Update' : 'Save'}
                        </button>
                    </div>
                </form>
            )}

            {/* Profiles list */}
            <div className="bg-slate-900/40 border border-slate-800/80 rounded-2xl overflow-hidden">
                {profiles.length === 0 ? (
                    <div className="text-center py-16 text-slate-500 text-sm space-y-2">
                        <p className="font-bold text-amber-400 uppercase tracking-wider text-xs">Not Configured</p>
                        <p>No Telegram Profiles created. Create one and mark it as Default to route security alerts.</p>
                    </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">Profile Name</th>
                                    <th className="py-3.5 px-4">Scope</th>
                                    <th className="py-3.5 px-4">Bot Token</th>
                                    <th className="py-3.5 px-4">Chat ID</th>
                                    <th className="py-3.5 px-4">Status</th>
                                    <th className="py-3.5 px-4">Last Notification</th>
                                    <th className="py-3.5 px-4">Associated Sites</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">
                                {profiles.map((profile) => (
                                    <tr key={profile.id} className="hover:bg-slate-800/10">
                                        <td className="py-3.5 px-4 font-semibold text-white">{profile.name}</td>
                                        <td className="py-3.5 px-4">
                                            {profile.is_default ? (
                                                <span className="inline-flex items-center gap-1.5 rounded-full border border-amber-500/20 bg-amber-500/10 px-2 py-1 text-[10px] font-bold uppercase text-amber-300">
                                                    <Star className="h-3 w-3" />
                                                    Default
                                                </span>
                                            ) : (
                                                <span className="inline-flex items-center gap-1.5 rounded-full border border-slate-700 bg-slate-950 px-2 py-1 text-[10px] font-bold uppercase text-slate-400">
                                                    <Globe2 className="h-3 w-3" />
                                                    Website
                                                </span>
                                            )}
                                        </td>
                                        <td className="py-3.5 px-4 font-mono text-xs text-slate-500 max-w-xs truncate" title={profile.bot_token}>
                                            {profile.bot_token}
                                        </td>
                                        <td className="py-3.5 px-4 font-mono text-xs text-slate-400 select-all">{profile.chat_id}</td>
                                        <td className="py-3.5 px-4">
                                            <ConnectionBadge status={profile.connection_status || 'unknown'} />
                                        </td>
                                        <td className="py-3.5 px-4 text-xs text-slate-400">
                                            {formatTimestamp(profile.last_notification_at)}
                                        </td>
                                        <td className="py-3.5 px-4 font-semibold text-slate-400">
                                            {profile.is_default ? 'Global fallback' : `${profile.agents_count} websites`}
                                        </td>
                                        <td className="py-3.5 px-4 text-right">
                                            <div className="flex justify-end gap-2.5">
                                                <button
                                                    onClick={() => handleVerify(profile.id)}
                                                    disabled={actionLoading[profile.id] === 'verify'}
                                                    className="p-1.5 rounded-lg border border-slate-800 text-slate-400 hover:text-emerald-400 hover:bg-emerald-500/10 transition-all disabled:opacity-50"
                                                    title="Verify Bot"
                                                >
                                                    {actionLoading[profile.id] === 'verify'
                                                        ? <Loader2 className="w-3.5 h-3.5 animate-spin" />
                                                        : <ShieldCheck className="w-3.5 h-3.5" />}
                                                </button>
                                                <button
                                                    onClick={() => handleSendTest(profile.id)}
                                                    disabled={actionLoading[profile.id] === 'test'}
                                                    className="p-1.5 rounded-lg border border-slate-800 text-slate-400 hover:text-sky-400 hover:bg-sky-500/10 transition-all disabled:opacity-50"
                                                    title="Send Test Notification"
                                                >
                                                    {actionLoading[profile.id] === 'test'
                                                        ? <Loader2 className="w-3.5 h-3.5 animate-spin" />
                                                        : <Send className="w-3.5 h-3.5" />}
                                                </button>
                                                <button
                                                    onClick={() => handleEdit(profile)}
                                                    className="p-1.5 rounded-lg border border-slate-800 text-slate-400 hover:text-white hover:bg-slate-800 transition-all"
                                                    title="Edit Profile"
                                                >
                                                    <Edit3 className="w-3.5 h-3.5" />
                                                </button>
                                                <button
                                                    onClick={() => handleDelete(profile.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 Profile"
                                                >
                                                    <Trash2 className="w-3.5 h-3.5" />
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                )}
            </div>
        </div>
    );
}
