import { useState, useEffect } from 'react';
import Head from 'next/head';
import Layout from '../components/Layout';
import { subscriptionAPI } from '../services/api';
import { useAuth } from '../hooks/useAuth';

export default function SubscriptionPage() {
    const { isPro } = useAuth();
    const [plans, setPlans] = useState<any[]>([]);
    const [payments, setPayments] = useState<any[]>([]);
    const [loading, setLoading] = useState(false);

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

    const loadData = async () => {
        try {
            const [planRes, payRes] = await Promise.all([
                subscriptionAPI.getPlans(),
                subscriptionAPI.getPayments(),
            ]);
            setPlans(planRes.data.data || []);
            setPayments(payRes.data.data?.payments || []);
        } catch (err) { console.error(err); }
    };

    const handleSubscribe = async (planId: string) => {
        setLoading(true);
        try {
            const { data } = await subscriptionAPI.subscribe(planId);
            if (data.data?.paymentUrl) {
                window.open(data.data.paymentUrl, '_blank');
            }
        } catch (err: any) {
            alert(err.response?.data?.message || 'Subscription failed');
        }
        setLoading(false);
    };

    const formatIDR = (n: number) => new Intl.NumberFormat('id-ID', { style: 'currency', currency: 'IDR', maximumFractionDigits: 0 }).format(n);

    return (
        <>
            <Head><title>Subscription – MarketScope</title></Head>
            <Layout>
                <div className="animate-fade-in">
                    <h1 className="text-2xl font-bold mb-2">Subscription Plans</h1>
                    <p className="text-gray-500 mb-8">Upgrade untuk fitur unlimited scan dan AI recommendation</p>

                    {/* Plans */}
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-10">
                        {plans.map((plan) => (
                            <div key={plan.id} className={`card relative overflow-hidden ${plan.id === 'PRO_MONTHLY' ? 'ring-2 ring-brand-primary' : ''}`}>
                                {plan.id === 'PRO_MONTHLY' && (
                                    <div className="absolute top-0 right-0 bg-gradient-to-r from-brand-primary to-brand-secondary text-white text-xs font-bold px-3 py-1 rounded-bl-lg">
                                        POPULAR
                                    </div>
                                )}
                                <div className="text-center">
                                    <h3 className="text-xl font-bold mb-1">{plan.name}</h3>
                                    <div className="mb-4">
                                        {plan.price === 0 ? (
                                            <span className="text-3xl font-bold text-gray-400">Gratis</span>
                                        ) : (
                                            <>
                                                <span className="text-3xl font-bold text-brand-primary">{formatIDR(plan.price)}</span>
                                                <span className="text-gray-500 text-sm">/{plan.id.includes('YEARLY') ? 'tahun' : 'bulan'}</span>
                                            </>
                                        )}
                                    </div>

                                    <ul className="text-left space-y-2 mb-6">
                                        {plan.features.map((f: string, i: number) => (
                                            <li key={i} className="text-sm text-gray-400 flex items-center gap-2">
                                                <span className="text-green-400">✓</span> {f}
                                            </li>
                                        ))}
                                    </ul>

                                    {plan.id === 'FREE' ? (
                                        <div className="btn-secondary w-full text-center cursor-default">Current Plan</div>
                                    ) : (
                                        <button
                                            onClick={() => handleSubscribe(plan.id)}
                                            disabled={loading || isPro}
                                            className="btn-primary w-full"
                                        >
                                            {isPro ? 'Active' : loading ? 'Processing...' : 'Subscribe'}
                                        </button>
                                    )}
                                </div>
                            </div>
                        ))}
                    </div>

                    {/* Payment History */}
                    <div className="card">
                        <h3 className="text-sm font-bold text-gray-400 uppercase tracking-wider mb-4">💳 Payment History</h3>
                        <div className="overflow-x-auto">
                            <table className="w-full">
                                <thead>
                                    <tr className="text-left text-xs text-gray-500 uppercase border-b border-dark-border">
                                        <th className="pb-3">Invoice</th>
                                        <th className="pb-3">Amount</th>
                                        <th className="pb-3">Method</th>
                                        <th className="pb-3">Status</th>
                                        <th className="pb-3">Date</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {payments.map((p: any) => (
                                        <tr key={p.id} className="border-b border-dark-border/50">
                                            <td className="py-3 pr-4 text-sm font-mono">{p.invoiceNumber}</td>
                                            <td className="py-3 pr-4 text-sm font-medium">{formatIDR(p.amount)}</td>
                                            <td className="py-3 pr-4 text-sm text-gray-400">{p.paymentMethod || '-'}</td>
                                            <td className="py-3 pr-4">
                                                <span className={`text-xs px-2 py-0.5 rounded ${p.status === 'PAID' ? 'bg-green-500/10 text-green-400' : p.status === 'PENDING' ? 'bg-yellow-500/10 text-yellow-400' : 'bg-red-500/10 text-red-400'}`}>
                                                    {p.status}
                                                </span>
                                            </td>
                                            <td className="py-3 text-xs text-gray-500">{new Date(p.createdAt).toLocaleDateString('id-ID')}</td>
                                        </tr>
                                    ))}
                                    {payments.length === 0 && (
                                        <tr><td colSpan={5} className="py-8 text-center text-gray-500">Belum ada riwayat pembayaran</td></tr>
                                    )}
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </Layout>
        </>
    );
}
