import { useCallback, useEffect, useState } from 'react';
import axios from '../../../bootstrap';
import { CheckCircle2, Loader2, Search, ShieldCheck, Trash2, ToggleLeft, ToggleRight } from 'lucide-react';

interface VerifiedSafeRecord {
    id: number;
    plugin_slug: string;
    plugin_name: string | null;
    plugin_version: string;
    relative_path: string;
    sha256: string;
    detection_rule: string | null;
    enabled: boolean;
    notes: string | null;
    created_at: string;
    verifier?: { id: number; name: string; email: string } | null;
}

export function VerifiedSafeFilesView() {
    const [records, setRecords] = useState<VerifiedSafeRecord[]>([]);
    const [isLoading, setIsLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);
    const [actionId, setActionId] = useState<number | null>(null);
    const [filters, setFilters] = useState({
        plugin: '',
        version: '',
        path: '',
        rule: '',
        status: '',
    });

    const fetchRecords = useCallback(async () => {
        setIsLoading(true);
        setError(null);

        try {
            const params = new URLSearchParams();
            Object.entries(filters).forEach(([key, value]) => {
                if (value.trim() !== '') {
                    params.set(key, value.trim());
                }
            });

            const query = params.toString();
            const res = await axios.get(`/verified-safe-files${query ? `?${query}` : ''}`);
            setRecords(res.data.records || []);
        } catch {
            setRecords([]);
            setError('Could not load verified safe fingerprints.');
        } finally {
            setIsLoading(false);
        }
    }, [filters]);

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

    const runAction = async (id: number, action: 'enable' | 'disable' | 'delete') => {
        setActionId(id);
        setError(null);

        try {
            if (action === 'delete') {
                await axios.delete(`/verified-safe-files/${id}`);
            } else {
                await axios.post(`/verified-safe-files/${id}/${action}`);
            }

            await fetchRecords();
        } catch (err: unknown) {
            const message = (err as { response?: { data?: { message?: string } } })?.response?.data?.message;
            setError(message || `Failed to ${action} fingerprint.`);
        } finally {
            setActionId(null);
        }
    };

    return (
        <div className="space-y-6">
            <div>
                <h3 className="text-xl font-bold text-white flex items-center gap-2">
                    <ShieldCheck className="w-5 h-5 text-emerald-400" />
                    Verified Safe Files
                </h3>
                <p className="text-sm text-slate-400 mt-1">
                    Cryptographic fingerprints trusted only when slug, version, path, and SHA-256 match exactly.
                </p>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-5 gap-3">
                {([
                    ['plugin', 'Plugin'],
                    ['version', 'Version'],
                    ['path', 'Path'],
                    ['rule', 'Rule'],
                ] as const).map(([key, label]) => (
                    <input
                        key={key}
                        value={filters[key]}
                        onChange={(e) => setFilters((prev) => ({ ...prev, [key]: e.target.value }))}
                        placeholder={`Search ${label}`}
                        className="rounded-xl border border-slate-800 bg-slate-900/60 px-3 py-2 text-sm text-slate-200"
                    />
                ))}
                <select
                    value={filters.status}
                    onChange={(e) => setFilters((prev) => ({ ...prev, status: e.target.value }))}
                    className="rounded-xl border border-slate-800 bg-slate-900/60 px-3 py-2 text-sm text-slate-200"
                >
                    <option value="">All statuses</option>
                    <option value="enabled">Enabled</option>
                    <option value="disabled">Disabled</option>
                </select>
            </div>

            <div className="flex gap-2">
                <button
                    onClick={() => fetchRecords()}
                    className="inline-flex items-center gap-2 rounded-xl border border-slate-700 px-3 py-2 text-sm text-slate-200 hover:bg-slate-800/60"
                >
                    <Search className="w-4 h-4" />
                    Search
                </button>
            </div>

            {error && (
                <div className="rounded-2xl border border-rose-500/20 bg-rose-500/5 px-4 py-3 text-sm text-rose-300">
                    {error}
                </div>
            )}

            <div className="bg-slate-900/40 border border-slate-800/80 rounded-2xl overflow-hidden">
                {isLoading ? (
                    <div className="flex justify-center items-center py-16">
                        <Loader2 className="w-8 h-8 animate-spin text-emerald-400" />
                    </div>
                ) : records.length === 0 ? (
                    <div className="text-center py-16 text-slate-500 text-sm">No verified safe fingerprints yet.</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 px-4">Plugin</th>
                                    <th className="py-3 px-4">Version</th>
                                    <th className="py-3 px-4">Relative Path</th>
                                    <th className="py-3 px-4">Rule</th>
                                    <th className="py-3 px-4">SHA-256</th>
                                    <th className="py-3 px-4">Verified By</th>
                                    <th className="py-3 px-4">Created</th>
                                    <th className="py-3 px-4">Status</th>
                                    <th className="py-3 px-4">Actions</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-slate-800/60 text-sm text-slate-300">
                                {records.map((record) => (
                                    <tr key={record.id} className="hover:bg-slate-800/10">
                                        <td className="py-3 px-4">
                                            <div className="font-semibold text-white">{record.plugin_name || record.plugin_slug}</div>
                                            <div className="text-[10px] text-slate-500 font-mono">{record.plugin_slug}</div>
                                        </td>
                                        <td className="py-3 px-4 font-mono text-xs">{record.plugin_version}</td>
                                        <td className="py-3 px-4 font-mono text-[10px] max-w-xs truncate" title={record.relative_path}>{record.relative_path}</td>
                                        <td className="py-3 px-4 text-xs">{record.detection_rule || '—'}</td>
                                        <td className="py-3 px-4 font-mono text-[10px] max-w-[120px] truncate" title={record.sha256}>{record.sha256}</td>
                                        <td className="py-3 px-4 text-xs">{record.verifier?.name || record.verifier?.email || '—'}</td>
                                        <td className="py-3 px-4 text-xs text-slate-500">{new Date(record.created_at).toLocaleString()}</td>
                                        <td className="py-3 px-4">
                                            <span className={`inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[10px] font-bold border ${
                                                record.enabled
                                                    ? 'bg-emerald-500/10 text-emerald-400 border-emerald-500/20'
                                                    : 'bg-slate-800 text-slate-400 border-slate-700'
                                            }`}>
                                                {record.enabled ? <CheckCircle2 className="w-3 h-3" /> : null}
                                                {record.enabled ? 'Enabled' : 'Disabled'}
                                            </span>
                                        </td>
                                        <td className="py-3 px-4">
                                            <div className="flex items-center gap-1">
                                                <button
                                                    disabled={actionId === record.id}
                                                    onClick={() => runAction(record.id, record.enabled ? 'disable' : 'enable')}
                                                    className="p-1.5 rounded-lg border border-slate-700 text-slate-300 hover:text-emerald-400"
                                                    title={record.enabled ? 'Disable' : 'Enable'}
                                                >
                                                    {record.enabled ? <ToggleRight className="w-4 h-4" /> : <ToggleLeft className="w-4 h-4" />}
                                                </button>
                                                <button
                                                    disabled={actionId === record.id}
                                                    onClick={() => runAction(record.id, 'delete')}
                                                    className="p-1.5 rounded-lg border border-slate-700 text-slate-300 hover:text-rose-400"
                                                    title="Delete"
                                                >
                                                    <Trash2 className="w-4 h-4" />
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                )}
            </div>
        </div>
    );
}
