import React, { useEffect, useState } from 'react';
import { CreditCard, ExternalLink, Calendar, CheckCircle2, History, AlertCircle, Loader2 } from 'lucide-react';
import { User } from '@/types';
import { supabase } from '@/lib/supabase';

interface DashboardSubscriptionProps {
    user: User;
    planName: string;
    t: any;
    handleStripePortal: () => void;
}

const DashboardSubscription: React.FC<DashboardSubscriptionProps> = ({ user, planName, t, handleStripePortal }) => {
    const [payments, setPayments] = useState<any[]>([]);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        const fetchPayments = async () => {
            try {
                const { data, error } = await supabase
                    .from('payments')
                    .select('*')
                    .order('created_at', { ascending: false });

                if (data) setPayments(data);
            } catch (error) {
                console.error("Error fetching payments:", error);
            } finally {
                setLoading(false);
            }
        };

        if (user.id) {
            fetchPayments();
        }
    }, [user.id]);

    const getStatusColor = (status: string) => {
        switch (status) {
            case 'completed': return 'bg-green-100 text-green-700';
            case 'pending': return 'bg-yellow-100 text-yellow-700';
            case 'failed': return 'bg-red-100 text-red-700';
            default: return 'bg-gray-100 text-gray-700';
        }
    };

    return (
        <div className="max-w-4xl mx-auto animate-in fade-in slide-in-from-bottom-4 duration-500 space-y-8">
            <header className="mb-8">
                <h1 className="text-3xl font-bold text-gray-900 mb-2">{t.dashboard.subTitle}</h1>
                <p className="text-gray-500 max-w-2xl">{t.dashboard.subDesc}</p>
            </header>

            {/* Current Plan Card */}
            <div className="bg-white rounded-3xl shadow-sm border border-gray-200 overflow-hidden relative">
                <div className="absolute top-0 right-0 p-8 opacity-5">
                    <CreditCard size={120} />
                </div>

                <div className="p-8 border-b border-gray-100 relative z-10">
                    <div className="flex justify-between items-start">
                        <div>
                            <div className="flex flex-col">
                                <h3 className="text-sm font-bold text-gray-500 uppercase tracking-widest mb-1">{t.dashboard.currentPlan}</h3>
                                <div className="flex items-center gap-3">
                                    <span className={`text-2xl font-bold ${planName === 'PRO' ? 'text-brand-600' : 'text-gray-900'}`}>
                                        {planName === 'PRO' ? 'Professional' : planName}
                                    </span>
                                </div>
                                {/* Check if user has a valid date and is NOT on free plan (unless free plan has an expiry which is rare but possible for trials) */}
                                {user.plan !== 'free' && user.plan_valid_until && (
                                    <p className="text-xs text-gray-400 mt-1">
                                        Válido até {new Date(user.plan_valid_until).toLocaleDateString('pt-BR')}
                                    </p>
                                )}
                            </div>
                            <div className="flex items-center gap-6">
                                <div className="flex items-center gap-2 text-gray-600 bg-gray-50 px-3 py-1.5 rounded-lg border border-gray-100">
                                    <Calendar size={16} className="text-brand-500" />
                                    <span className="text-sm font-medium">
                                        {user.plan_valid_until
                                            ? `${t.dashboard.validUntil} ${new Date(user.plan_valid_until).toLocaleDateString('pt-BR')}`
                                            : t.dashboard.limitedAccess}
                                    </span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div className="bg-gray-50/50 p-6 flex flex-col sm:flex-row items-center justify-between gap-4">
                    <p className="text-sm text-gray-500 max-w-md">
                        Gerencie sua assinatura e métodos de pagamento através do portal seguro.
                    </p>
                    <button
                        onClick={handleStripePortal}
                        className="bg-white border border-gray-200 text-gray-900 font-bold px-5 py-2.5 rounded-xl hover:bg-gray-50 hover:border-gray-300 transition-all flex items-center gap-2 text-sm shadow-sm"
                    >
                        <ExternalLink size={16} />
                        {t.dashboard.btnPortal}
                    </button>
                </div>
            </div>

            {/* Payment History */}
            <div className="bg-white rounded-3xl shadow-sm border border-gray-200 overflow-hidden">
                <div className="p-6 border-b border-gray-100 flex items-center justify-between">
                    <h3 className="font-bold text-lg text-gray-900 flex items-center gap-2">
                        <History size={20} className="text-gray-400" />
                        Histórico de Pagamentos
                    </h3>
                </div>

                {loading ? (
                    <div className="p-12 flex justify-center text-gray-400">
                        <Loader2 className="animate-spin" size={24} />
                    </div>
                ) : payments.length === 0 ? (
                    <div className="p-12 text-center text-gray-400">
                        <AlertCircle size={32} className="mx-auto mb-3 opacity-20" />
                        <p>Nenhum pagamento registrado ainda.</p>
                    </div>
                ) : (
                    <div className="overflow-x-auto">
                        <table className="w-full text-left">
                            <thead className="bg-gray-50/50 text-gray-500 text-xs uppercase font-bold tracking-wider">
                                <tr>
                                    <th className="px-6 py-4">Data</th>
                                    <th className="px-6 py-4">Valor</th>
                                    <th className="px-6 py-4">Plano</th>
                                    <th className="px-6 py-4 text-right">Status</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-gray-100 text-sm">
                                {payments.map((payment) => (
                                    <tr key={payment.id} className="hover:bg-gray-50/50 transition-colors">
                                        <td className="px-6 py-4 font-medium text-gray-900">
                                            {new Date(payment.created_at).toLocaleDateString('pt-BR')}
                                        </td>
                                        <td className="px-6 py-4 text-gray-600">
                                            R$ {payment.amount.toFixed(2)}
                                        </td>
                                        <td className="px-6 py-4 capitalize text-gray-600">
                                            {payment.plan_type}
                                        </td>
                                        <td className="px-6 py-4 text-right">
                                            <span className={`inline-flex px-2 py-1 rounded-full text-xs font-bold uppercase tracking-wider ${getStatusColor(payment.status)}`}>
                                                {payment.status === 'completed' ? 'Pago' : payment.status}
                                            </span>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                )}
            </div>

            {/* Upgrade Banner (Conditional) */}
            {user.plan === 'free' && (
                <div className="bg-gradient-to-r from-gray-900 to-gray-800 rounded-3xl p-8 text-white relative overflow-hidden shadow-xl">
                    <div className="relative z-10 flex flex-col md:flex-row items-center justify-between gap-6">
                        <div>
                            <h3 className="text-xl font-bold mb-2 flex items-center gap-2">
                                <CheckCircle2 className="text-green-400" />
                                Desbloqueie todo o potencial
                            </h3>
                            <p className="text-gray-300 max-w-lg text-sm leading-relaxed">
                                Obtenha análises ilimitadas, histórico completo e acesso às funcionalidades profissionais.
                            </p>
                        </div>
                        <button
                            onClick={async () => {
                                try {
                                    const { data: { session } } = await supabase.auth.getSession();
                                    if (!session) return alert("Faça login novamente");

                                    const res = await fetch(`${import.meta.env.VITE_SUPABASE_URL}/functions/v1/stripe-checkout`, {
                                        method: "POST",
                                        headers: {
                                            "Content-Type": "application/json",
                                            "Authorization": `Bearer ${session.access_token}`,
                                        },
                                        body: JSON.stringify({ plan: "mensal" }) // Default to monthly
                                    });

                                    const { url, error } = await res.json();
                                    if (error) throw new Error(error);
                                    if (url) window.location.href = url;
                                } catch (e) {
                                    alert("Erro ao iniciar checkout: " + e);
                                }
                            }}
                            className="bg-white hover:bg-gray-100 text-gray-900 font-bold px-8 py-3 rounded-xl transition-all shadow-lg hover:shadow-xl hover:-translate-y-0.5 whitespace-nowrap"
                        >
                            Fazer Upgrade Agora
                        </button>
                    </div>
                    {/* Decorative BG */}
                    <div className="absolute top-0 right-0 w-64 h-64 bg-white rounded-full blur-[100px] opacity-10 translate-x-1/2 -translate-y-1/2"></div>
                </div>
            )}
        </div>
    );
};

export default DashboardSubscription;
