'use client';

import { useState, useEffect } from 'react';
import { toast } from 'react-hot-toast';
import {
    Search,
    Filter,
    ChevronDown,
    ChevronUp,
    DollarSign,
    Clock,
    FileText,
    Image as ImageIcon,
    Video,
    Mic,
    Cpu
} from 'lucide-react';
import AdminGuard from '@/components/AdminGuard';
import api from '@/lib/api';

interface UsageLog {
    id: string;
    timestamp: string;
    user: {
        id: string;
        email: string;
        name: string;
    };
    service: {
        module: string;
        provider: string;
        model: string;
    };
    metrics: {
        tokens_in?: number;
        tokens_out?: number;
        cost_usd: number;
        latency_ms: number;
    };
    request_details: any;
    response_details: any;
}

export default function UsageSearchPage() {
    const [logs, setLogs] = useState<UsageLog[]>([]);
    const [loading, setLoading] = useState(false);
    const [searchQuery, setSearchQuery] = useState('');
    const [expandedRow, setExpandedRow] = useState<string | null>(null);

    // Filters
    const [providerFilter, setProviderFilter] = useState('');
    const [startDate, setStartDate] = useState('');

    const searchLogs = async () => {
        setLoading(true);
        try {
            const params: any = {
                limit: 50
            };

            if (searchQuery) params.query = searchQuery;
            if (providerFilter) params.provider = providerFilter;
            if (startDate) params.start_date = new Date(startDate).toISOString();

            const response = await api.get('/admin/logs/search', { params });
            setLogs(response.data.items || []);
        } catch (error) {
            console.error('Search failed', error);
            toast.error('Failed to search logs');
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        searchLogs();
    }, []); // Initial load

    const toggleRow = (id: string) => {
        setExpandedRow(expandedRow === id ? null : id);
    };

    const getModuleIcon = (module: string) => {
        if (module.includes('image')) return <ImageIcon className="w-4 h-4 text-purple-400" />;
        if (module.includes('video')) return <Video className="w-4 h-4 text-pink-400" />;
        if (module.includes('voice') || module.includes('speech')) return <Mic className="w-4 h-4 text-yellow-400" />;
        if (module.includes('text')) return <FileText className="w-4 h-4 text-blue-400" />;
        return <Cpu className="w-4 h-4 text-gray-400" />;
    };

    const formatMetadata = (data: any) => {
        if (!data) return <span className="text-gray-500 italic">No data</span>;
        return (
            <div className="grid grid-cols-1 gap-2 text-sm">
                {Object.entries(data).map(([key, value]) => (
                    <div key={key} className="flex flex-col">
                        <span className="text-gray-500 uppercase text-xs font-bold">{key.replace(/_/g, ' ')}</span>
                        <span className="text-gray-300 break-words font-mono bg-black/20 p-1 rounded mt-1">
                            {typeof value === 'object' ? JSON.stringify(value, null, 2) : String(value)}
                        </span>
                    </div>
                ))}
            </div>
        );
    };

    return (
        <AdminGuard>
            <div className="space-y-6">
                <div className="flex items-center justify-between">
                    <div>
                        <h1 className="text-2xl font-bold text-white">AI Usage Explorer</h1>
                        <p className="text-gray-500">Search prompts, files, and costs</p>
                    </div>
                </div>

                {/* Search Bar */}
                <div className="bg-forge-dark p-4 rounded-xl border border-gray-800 flex flex-wrap gap-4 items-end">
                    <div className="flex-1 min-w-[300px]">
                        <label className="block text-sm text-gray-500 mb-1">Search Keywords</label>
                        <div className="relative">
                            <Search className="absolute left-3 top-3 w-5 h-5 text-gray-500" />
                            <input
                                type="text"
                                placeholder="Search prompts, filenames, user emails..."
                                className="input-field pl-10 w-full"
                                value={searchQuery}
                                onChange={(e) => setSearchQuery(e.target.value)}
                                onKeyDown={(e) => e.key === 'Enter' && searchLogs()}
                            />
                        </div>
                    </div>

                    <div className="w-48">
                        <label className="block text-sm text-gray-500 mb-1">Provider</label>
                        <select
                            className="select-field w-full"
                            value={providerFilter}
                            onChange={(e) => setProviderFilter(e.target.value)}
                        >
                            <option value="">All Providers</option>
                            <option value="openai">OpenAI</option>
                            <option value="google">Google</option>
                            <option value="elevenlabs">ElevenLabs</option>
                            <option value="topaz">Topaz</option>
                            <option value="runway">Runway</option>
                            <option value="stability">Stability AI</option>
                        </select>
                    </div>

                    <div className="w-48">
                        <label className="block text-sm text-gray-500 mb-1">Start Date</label>
                        <input
                            type="date"
                            className="input-field w-full"
                            value={startDate}
                            onChange={(e) => setStartDate(e.target.value)}
                        />
                    </div>

                    <button
                        onClick={searchLogs}
                        disabled={loading}
                        className="btn-primary h-[42px] px-6"
                    >
                        {loading ? 'Searching...' : 'Search'}
                    </button>
                </div>

                {/* Results Table */}
                <div className="bg-forge-dark rounded-xl border border-gray-800 overflow-hidden">
                    <table className="w-full">
                        <thead className="bg-black/20">
                            <tr>
                                <th className="px-6 py-3 text-left text-sm font-medium text-gray-500">Time</th>
                                <th className="px-6 py-3 text-left text-sm font-medium text-gray-500">User</th>
                                <th className="px-6 py-3 text-left text-sm font-medium text-gray-500">Service / Model</th>
                                <th className="px-6 py-3 text-right text-sm font-medium text-gray-500">Cost</th>
                                <th className="px-6 py-3 text-right text-sm font-medium text-gray-500">Latency</th>
                                <th className="px-6 py-3 w-10"></th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-gray-800">
                            {logs.length === 0 && !loading && (
                                <tr>
                                    <td colSpan={6} className="px-6 py-12 text-center text-gray-500">
                                        No logs found. Try adjusting your search query.
                                    </td>
                                </tr>
                            )}

                            {logs.map((log) => (
                                <>
                                    <tr
                                        key={log.id}
                                        onClick={() => toggleRow(log.id)}
                                        className="hover:bg-white/5 cursor-pointer transition-colors"
                                    >
                                        <td className="px-6 py-4 text-sm text-gray-300">
                                            {new Date(log.timestamp).toLocaleString()}
                                        </td>
                                        <td className="px-6 py-4">
                                            <div className="text-sm text-white">{log.user.name || log.user.email}</div>
                                            <div className="text-xs text-gray-500">{log.user.email}</div>
                                        </td>
                                        <td className="px-6 py-4">
                                            <div className="flex items-center gap-2">
                                                {getModuleIcon(log.service.module)}
                                                <span className="text-sm text-white font-medium">{log.service.provider}</span>
                                            </div>
                                            <div className="text-xs text-forge-yellow mt-1 pl-6">{log.service.model}</div>
                                        </td>
                                        <td className="px-6 py-4 text-right">
                                            <div className="flex items-center justify-end gap-1 text-sm text-green-400 font-mono">
                                                <DollarSign className="w-3 h-3" />
                                                {log.metrics.cost_usd.toFixed(4)}
                                            </div>
                                        </td>
                                        <td className="px-6 py-4 text-right">
                                            <div className="flex items-center justify-end gap-1 text-sm text-gray-400">
                                                <Clock className="w-3 h-3" />
                                                {log.metrics.latency_ms}ms
                                            </div>
                                        </td>
                                        <td className="px-6 py-4">
                                            {expandedRow === log.id ? <ChevronUp className="w-4 h-4 text-gray-500" /> : <ChevronDown className="w-4 h-4 text-gray-500" />}
                                        </td>
                                    </tr>

                                    {expandedRow === log.id && (
                                        <tr className="bg-black/20">
                                            <td colSpan={6} className="px-6 py-4 border-b border-gray-800">
                                                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                                    {/* Request Details */}
                                                    <div className="bg-forge-darker rounded-lg p-4 border border-gray-700/50">
                                                        <h4 className="text-gray-400 text-xs uppercase font-semibold mb-3 border-b border-gray-700 pb-2">Request Parameters</h4>
                                                        {formatMetadata(log.request_details)}

                                                        {/* Show Prompt Prominently if exists */}
                                                        {log.request_details?.prompt && (
                                                            <div className="mt-4 pt-4 border-t border-gray-700/50">
                                                                <div className="text-gray-500 uppercase text-xs font-bold mb-1">Full Prompt</div>
                                                                <div className="text-white text-sm bg-black/30 p-3 rounded border border-gray-700/50 leading-relaxed max-h-32 overflow-y-auto">
                                                                    {log.request_details.prompt}
                                                                </div>
                                                            </div>
                                                        )}
                                                    </div>

                                                    {/* Response Details */}
                                                    <div className="bg-forge-darker rounded-lg p-4 border border-gray-700/50">
                                                        <h4 className="text-gray-400 text-xs uppercase font-semibold mb-3 border-b border-gray-700 pb-2">Response & Output</h4>
                                                        {formatMetadata(log.response_details)}
                                                    </div>
                                                </div>
                                            </td>
                                        </tr>
                                    )}
                                </>
                            ))}
                        </tbody>
                    </table>
                </div>
            </div>
        </AdminGuard>
    );
}
