'use client';

import { useState, useEffect } from 'react';
import { Edit, Plus, Search, X, Check, AlertCircle } from 'lucide-react';
import { updateUserCredits, setUserDailyLimit, setUserApiCosts } from '@/services/admin-credit-service';
import { setUserPlan, getUserSubscription, type SubscriptionPlan } from '@/services/subscription-service';

interface User {
    id: string;
    email: string;
    username: string;
    balance: number;
    total_purchased: number;
    total_used: number;
    daily_limit: number | null;
    google_search_cost: number;
    gemini_ai_cost: number;
    last_active?: string;
}

interface UserManagementClientProps {
    initialUsers: User[];
    plans: SubscriptionPlan[];
}

export default function UserManagementClient({ initialUsers, plans }: UserManagementClientProps) {
    const [users, setUsers] = useState<User[]>(initialUsers);
    const [searchTerm, setSearchTerm] = useState('');
    const [editingUser, setEditingUser] = useState<User | null>(null);
    const [creditAmount, setCreditAmount] = useState('');
    const [reason, setReason] = useState('');
    const [dailyLimit, setDailyLimit] = useState('');
    const [googleCost, setGoogleCost] = useState('');
    const [geminiCost, setGeminiCost] = useState('');
    const [selectedPlan, setSelectedPlan] = useState('');
    const [currentPlan, setCurrentPlan] = useState<SubscriptionPlan | null>(null);
    const [loading, setLoading] = useState(false);
    const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);

    const filteredUsers = users.filter(user =>
        user.email.toLowerCase().includes(searchTerm.toLowerCase()) ||
        user.username.toLowerCase().includes(searchTerm.toLowerCase())
    );

    // Load user's current plan when editing
    useEffect(() => {
        if (editingUser) {
            getUserSubscription(editingUser.id).then(({ plan }) => {
                setCurrentPlan(plan);
                setSelectedPlan(plan?.id || '');
            });
        }
    }, [editingUser]);

    const handleEditUser = (user: User) => {
        setEditingUser(user);
        setCreditAmount('');
        setReason('');
        setDailyLimit(user.daily_limit?.toString() || '');
        setGoogleCost(user.google_search_cost.toString());
        setGeminiCost(user.gemini_ai_cost.toString());
        setMessage(null);
    };

    const handleUpdatePlan = async () => {
        if (!editingUser || !selectedPlan) {
            setMessage({ type: 'error', text: 'Please select a plan' });
            return;
        }

        setLoading(true);
        setMessage(null);

        const result = await setUserPlan(editingUser.id, selectedPlan);

        if (result.success) {
            setMessage({ type: 'success', text: 'Plan updated successfully' });
            // Reload current plan
            const { plan } = await getUserSubscription(editingUser.id);
            setCurrentPlan(plan);
        } else {
            setMessage({ type: 'error', text: result.error || 'Failed to update plan' });
        }

        setLoading(false);
    };

    const handleUpdateCredits = async () => {
        if (!editingUser || !creditAmount || !reason) {
            setMessage({ type: 'error', text: 'Please fill in all fields' });
            return;
        }

        setLoading(true);
        setMessage(null);

        const amount = parseInt(creditAmount);
        const newBalance = editingUser.balance + amount;

        const result = await updateUserCredits(editingUser.id, newBalance, reason);

        if (result.success) {
            // Update local state
            setUsers(users.map(u =>
                u.id === editingUser.id
                    ? { ...u, balance: newBalance, total_purchased: u.total_purchased + (amount > 0 ? amount : 0) }
                    : u
            ));
            setMessage({ type: 'success', text: `Successfully ${amount > 0 ? 'added' : 'removed'} ${Math.abs(amount)} credits` });
            setCreditAmount('');
            setReason('');
        } else {
            setMessage({ type: 'error', text: result.error || 'Failed to update credits' });
        }

        setLoading(false);
    };

    const handleUpdateSettings = async () => {
        if (!editingUser) return;

        setLoading(true);
        setMessage(null);

        // Update daily limit
        if (dailyLimit !== (editingUser.daily_limit?.toString() || '')) {
            const limitValue = dailyLimit === '' ? null : parseInt(dailyLimit);
            const limitResult = await setUserDailyLimit(editingUser.id, limitValue);
            if (!limitResult.success) {
                setMessage({ type: 'error', text: 'Failed to update daily limit' });
                setLoading(false);
                return;
            }
        }

        // Update API costs
        if (googleCost !== editingUser.google_search_cost.toString() || geminiCost !== editingUser.gemini_ai_cost.toString()) {
            const costsResult = await setUserApiCosts(
                editingUser.id,
                parseInt(googleCost),
                parseInt(geminiCost)
            );
            if (!costsResult.success) {
                setMessage({ type: 'error', text: 'Failed to update API costs' });
                setLoading(false);
                return;
            }
        }

        // Update local state
        setUsers(users.map(u =>
            u.id === editingUser.id
                ? {
                    ...u,
                    daily_limit: dailyLimit === '' ? null : parseInt(dailyLimit),
                    google_search_cost: parseInt(googleCost),
                    gemini_ai_cost: parseInt(geminiCost)
                }
                : u
        ));

        setMessage({ type: 'success', text: 'Settings updated successfully' });
        setLoading(false);
    };

    return (
        <div className="space-y-6">
            {/* Search Bar */}
            <div className="bg-zinc-900 rounded-[32px] p-6 border border-zinc-800 shadow-sm">
                <div className="relative">
                    <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-zinc-500" size={20} />
                    <input
                        type="text"
                        placeholder="Search users by email or username..."
                        value={searchTerm}
                        onChange={(e) => setSearchTerm(e.target.value)}
                        className="w-full pl-10 pr-4 py-3 bg-zinc-800 border border-zinc-700 rounded-2xl text-sm focus:outline-none focus:ring-2 focus:ring-orange-600/50 text-white"
                    />
                </div>
            </div>

            {/* User Table */}
            <div className="bg-zinc-900 rounded-[32px] p-6 border border-zinc-800 shadow-sm overflow-hidden">
                <h2 className="text-xl font-bold text-white uppercase tracking-tighter mb-6">Users ({filteredUsers.length})</h2>
                <div className="overflow-x-auto -mx-6">
                    <table className="w-full">
                        <thead>
                            <tr className="border-b border-zinc-800">
                                <th className="text-left py-4 px-6 text-[10px] font-bold uppercase tracking-widest text-zinc-500">User</th>
                                <th className="text-left py-4 px-6 text-[10px] font-bold uppercase tracking-widest text-zinc-500">Balance</th>
                                <th className="text-left py-4 px-6 text-[10px] font-bold uppercase tracking-widest text-zinc-500">Used</th>
                                <th className="text-left py-4 px-6 text-[10px] font-bold uppercase tracking-widest text-zinc-500">Daily Limit</th>
                                <th className="text-left py-4 px-6 text-[10px] font-bold uppercase tracking-widest text-zinc-500">Costs</th>
                                <th className="text-right py-4 px-6 text-[10px] font-bold uppercase tracking-widest text-zinc-500">Actions</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-zinc-800/50">
                            {filteredUsers.map((user) => (
                                <tr key={user.id} className="hover:bg-zinc-800/30 transition-colors">
                                    <td className="py-4 px-6">
                                        <div>
                                            <div className="font-bold text-white uppercase tracking-tight text-sm">{user.username}</div>
                                            <div className="text-[10px] font-medium text-zinc-500">{user.email}</div>
                                        </div>
                                    </td>
                                    <td className="py-4 px-6">
                                        <span className={`text-lg font-bold tracking-tighter ${user.balance < 10 ? 'text-red-500' : 'text-orange-600'}`}>
                                            {user.balance}
                                        </span>
                                    </td>
                                    <td className="py-4 px-6 text-sm font-medium text-zinc-400">
                                        {user.total_used}
                                    </td>
                                    <td className="py-4 px-6 text-xs text-zinc-500 uppercase tracking-widest">
                                        {user.daily_limit || 'Global (80)'}
                                    </td>
                                    <td className="py-4 px-6 text-[10px] font-bold text-zinc-600 uppercase tracking-widest">
                                        G:{user.google_search_cost} / AI:{user.gemini_ai_cost}
                                    </td>
                                    <td className="py-4 px-6 text-right">
                                        <button
                                            onClick={() => handleEditUser(user)}
                                            className="inline-flex items-center gap-2 px-4 py-2 bg-orange-600 hover:bg-orange-700 text-white rounded-xl text-[10px] font-bold uppercase tracking-widest transition-all shadow-md shadow-orange-950/20"
                                        >
                                            <Edit size={14} />
                                            Edit
                                        </button>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            </div>

            {/* Edit Modal */}
            {editingUser && (
                <div className="fixed inset-0 bg-black/80 backdrop-blur-sm flex items-center justify-center p-4 z-50">
                    <div className="bg-zinc-900 rounded-[32px] p-8 max-w-2xl w-full max-h-[90vh] overflow-y-auto border border-zinc-800 shadow-2xl space-y-8">
                        <div className="flex items-center justify-between">
                            <div>
                                <h3 className="text-2xl font-bold text-white uppercase tracking-tighter">Edit User</h3>
                                <p className="text-[10px] font-bold text-zinc-500 uppercase tracking-widest mt-1">{editingUser.email}</p>
                            </div>
                            <button
                                onClick={() => setEditingUser(null)}
                                className="p-2 hover:bg-zinc-800 rounded-xl transition-colors text-zinc-500"
                            >
                                <X size={24} />
                            </button>
                        </div>

                        {message && (
                            <div className={`mb-4 p-4 rounded-xl flex items-center gap-3 ${message.type === 'success'
                                ? 'bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-500'
                                : 'bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-500'
                                }`}>
                                {message.type === 'success' ? <Check size={20} /> : <AlertCircle size={20} />}
                                {message.text}
                            </div>
                        )}

                        <div className="space-y-6">
                            {/* Current Balance */}
                            <div className="p-6 bg-zinc-800/50 rounded-2xl border border-zinc-800">
                                <div className="text-[10px] font-bold uppercase text-zinc-500 tracking-widest mb-1">Current Balance</div>
                                <div className="text-4xl font-bold text-orange-600 tracking-tighter">{editingUser.balance} <span className="text-xl text-zinc-500 ml-1">Credits</span></div>
                            </div>

                            {/* Add/Remove Credits */}
                            <div className="space-y-4">
                                <h4 className="text-[10px] font-bold text-zinc-500 uppercase tracking-widest">Adjust Credits</h4>
                                <div className="grid grid-cols-2 gap-4">
                                    <div>
                                        <label className="block text-[8px] font-bold text-zinc-600 uppercase tracking-widest mb-1 ml-1">Amount</label>
                                        <input
                                            type="number"
                                            value={creditAmount}
                                            onChange={(e) => setCreditAmount(e.target.value)}
                                            placeholder="e.g. 100 or -50"
                                            className="w-full px-4 py-2 bg-zinc-800 border border-zinc-700 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-orange-600/50 text-white"
                                        />
                                    </div>
                                    <div>
                                        <label className="block text-[8px] font-bold text-zinc-600 uppercase tracking-widest mb-1 ml-1">Reason</label>
                                        <input
                                            type="text"
                                            value={reason}
                                            onChange={(e) => setReason(e.target.value)}
                                            placeholder="e.g. Monthly bonus"
                                            className="w-full px-4 py-2 bg-zinc-800 border border-zinc-700 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-orange-600/50 text-white"
                                        />
                                    </div>
                                </div>
                                <button
                                    onClick={handleUpdateCredits}
                                    disabled={loading || !creditAmount || !reason}
                                    className="w-full py-4 bg-orange-600 hover:bg-orange-700 text-white font-bold rounded-2xl transition-all shadow-lg shadow-orange-950/20 disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
                                >
                                    <Plus size={18} />
                                    Update Credits
                                </button>
                            </div>

                            <hr className="border-zinc-200 dark:border-zinc-800" />

                            {/* Subscription Plan */}
                            <div className="space-y-4">
                                <h4 className="text-[10px] font-bold text-zinc-500 uppercase tracking-widest">Subscription Plan</h4>
                                {currentPlan && (
                                    <div className="p-4 bg-orange-900/20 rounded-2xl border border-orange-500/30">
                                        <div className="text-[10px] font-bold text-orange-400 uppercase tracking-widest mb-1">Current Plan</div>
                                        <div className="text-xl font-bold text-orange-100 uppercase tracking-tight">{currentPlan.display_name}</div>
                                        <div className="text-[10px] font-bold text-orange-400/60 uppercase tracking-widest mt-1">{currentPlan.monthly_credits} credits/month</div>
                                    </div>
                                )}
                                <div>
                                    <label className="block text-[8px] font-bold text-zinc-600 uppercase tracking-widest mb-1 ml-1">Assign Plan</label>
                                    <select
                                        value={selectedPlan}
                                        onChange={(e) => setSelectedPlan(e.target.value)}
                                        className="w-full px-4 py-3 bg-zinc-800 border border-zinc-700 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-orange-600/50 text-white appearance-none"
                                    >
                                        <option value="">Select a plan...</option>
                                        {plans.map(plan => (
                                            <option key={plan.id} value={plan.id}>
                                                {plan.display_name} - {plan.monthly_credits} credits/month (€{plan.price})
                                            </option>
                                        ))}
                                    </select>
                                </div>
                                <button
                                    onClick={handleUpdatePlan}
                                    disabled={loading || !selectedPlan}
                                    className="w-full py-3 bg-purple-600 hover:bg-purple-700 text-white font-bold rounded-xl transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
                                >
                                    <Check size={18} />
                                    Update Plan
                                </button>
                            </div>

                            <hr className="border-zinc-200 dark:border-zinc-800" />

                            {/* Settings */}
                            <div className="space-y-4">
                                <h4 className="text-[10px] font-bold text-zinc-500 uppercase tracking-widest">User Settings</h4>
                                <div className="grid grid-cols-3 gap-4">
                                    <div>
                                        <label className="block text-[8px] font-bold text-zinc-600 uppercase tracking-widest mb-1 ml-1">Daily Limit</label>
                                        <input
                                            type="number"
                                            value={dailyLimit}
                                            onChange={(e) => setDailyLimit(e.target.value)}
                                            placeholder="Global (80)"
                                            className="w-full px-4 py-2 bg-zinc-800 border border-zinc-700 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-orange-600/50 text-white"
                                        />
                                    </div>
                                    <div>
                                        <label className="block text-[8px] font-bold text-zinc-600 uppercase tracking-widest mb-1 ml-1">Google Cost</label>
                                        <input
                                            type="number"
                                            value={googleCost}
                                            onChange={(e) => setGoogleCost(e.target.value)}
                                            className="w-full px-4 py-2 bg-zinc-800 border border-zinc-700 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-orange-600/50 text-white"
                                        />
                                    </div>
                                    <div>
                                        <label className="block text-[8px] font-bold text-zinc-600 uppercase tracking-widest mb-1 ml-1">Gemini Cost</label>
                                        <input
                                            type="number"
                                            value={geminiCost}
                                            onChange={(e) => setGeminiCost(e.target.value)}
                                            className="w-full px-4 py-2 bg-zinc-800 border border-zinc-700 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-orange-600/50 text-white"
                                        />
                                    </div>
                                </div>
                                <button
                                    onClick={handleUpdateSettings}
                                    disabled={loading}
                                    className="w-full py-4 bg-zinc-800 hover:bg-zinc-700 text-white font-bold rounded-2xl transition-all border border-zinc-700 disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
                                >
                                    <Check size={18} />
                                    Save Settings
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}
