'use client';

import React, { useState } from 'react';
import Image from 'next/image';
import { useRouter } from 'next/navigation';
import { useAuthStore } from '@/stores/authStore';

// Import payment method logos
import paypalIcon from '../../../public/images/payments/paypal.png';
import paystackIcon from '../../../public/images/payments/paystack.png';
import flutterwaveIcon from '../../../public/images/payments/flutterwave.png';
import remitaIcon from '../../../public/images/payments/remita.png';
import pagaIcon from '../../../public/images/payments/paga.png';

const plans = [
  {
    id: 'membership',
    name: 'Membership',
    price: 1000,
    duration: '3 Months',
    type: 'Quaterly (3 Months)',
    features: [
      'Required to access Med Bridge Afrik services',
      'Basic onboarding and support',
    ],
  },
  {
    id: 'triage',
    name: 'Triage',
    price: 45000,
    duration: '3 Months',
    type: 'Pay-as-you-Go',
    features: [
      'Initial condition assessment',
      'Diagnosis by certified clinicians',
      'Next-step recommendations',
    ],
  },
  {
    id: 'guidance',
    name: 'Guidance & Next Steps',
    price: 15000,
    duration: '3 Months',
    type: 'Pay-as-you-Go',
    features: [
      'Expert medical advice',
      'Treatment or referral plan',
      'Short-term monitoring guidance',
    ],
  },
  {
    id: 'speaking',
    name: 'Speaking Only (Video & Text)',
    price: 10000,
    duration: '3 Months',
    type: 'Pay-as-you-Go',
    features: [
      'Text and video chat with a doctor',
      'E-Prescriptions and diagnostics',
      'Quick doctor-callout or second opinions',
    ],
  },
];

const paymentMethods = [
  { name: 'PayPal', icon: paypalIcon },
  { name: 'Paystack', icon: paystackIcon },
  { name: 'Flutterwave', icon: flutterwaveIcon },
  { name: 'Remita', icon: remitaIcon },
  { name: 'Paga', icon: pagaIcon },
];

const PatientSubscription = () => {
  const [selectedPlan, setSelectedPlan] = useState(null);
  const [modalOpen, setModalOpen] = useState(false);
  const router = useRouter();

  const userData = useAuthStore((state) => state.user);
  const user = userData?.profile || null;
  // console.log('User Data:', user);
  const handlePlanSelect = (plan) => {

    setSelectedPlan(plan);
    setModalOpen(true);

  };

  const handlePaymentMethod = async (method) => {

    const payload = {
      userId: user.id,
      planId: selectedPlan.id,
      planName: selectedPlan.name,
      amount: selectedPlan.price,
      duration: selectedPlan.duration,
      paymentMethod: method,
    };

    try {
      const res = await fetch('/api/subscribe', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });

      const data = await res.json();

      if (!res.ok) throw new Error(data.message || 'Payment failed');

      setModalOpen(false);
      alert(`Redirecting to ${method} gateway...`);
      router.push(data.redirectUrl);
      // api/paypal
      // api/paystack
      // api/flutterwave
      // api/remita
      // api/paga

    } catch (err) {
      alert(`Error: ${err.message}`);
    }
  };

  return (
    <div className="max-w-6xl mx-auto p-6 relative">
      <h2 className="text-3xl font-bold text-center mb-6 text-indigo-700">
        Med Bridge Afrik Subscription Plans
      </h2>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        {plans.map((plan) => (
          <div
            key={plan.id}
            className="border rounded-2xl shadow p-5 hover:shadow-lg transition"
          >
            <h3 className="text-xl font-semibold text-gray-800 mb-2">{plan.name}</h3>
            <p className="text-indigo-600 text-2xl font-bold mb-1">
              ₦{plan.price.toLocaleString()}
            </p>

            <p className="text-gray-500 text-sm italic mb-4">{plan.coverage}</p>
            <p className="text-gray-600 mb-2">
              {/* <strong>Duration:</strong> {plan.duration} */}
            </p>
            <h4 className="text-gray-700 font-medium mb-2">Features:</h4>
            <ul className="list-disc list-inside text-sm text-gray-700 mb-4">
              {plan.features.map((feature, idx) => (
                <li key={idx}>{feature}</li>
              ))}
            </ul>
            <button
              onClick={() => handlePlanSelect(plan)}
              className="bg-indigo-600 text-white w-full py-2 rounded-lg hover:bg-indigo-700 transition"
            >
              Pay Now
            </button>
          </div>
        ))}
      </div>

      {modalOpen && selectedPlan && (
        <div className="fixed inset-0 z-50 bg-black/50 flex items-center justify-center px-4">
          <div className="bg-white p-6 rounded-xl w-full max-w-md shadow-xl relative">
            <button
              onClick={() => setModalOpen(false)}
              className="absolute top-3 right-3 text-gray-500 hover:text-black"
            >
              ✕
            </button>
            <h3 className="text-xl font-bold text-indigo-700 mb-2">
              Choose Payment Method
            </h3>
            <p className="text-gray-700 mb-4">
              You selected <strong>{selectedPlan.name}</strong> — ₦
              {selectedPlan.price.toLocaleString()}
            </p>

            <div className="grid grid-cols-2 gap-3">
              {paymentMethods.map(({ name, icon }) => (
                <button
                  key={name}
                  onClick={() => handlePaymentMethod(name)}
                  className="border border-indigo-500 text-indigo-700 font-medium py-3 px-4 rounded flex items-center justify-start gap-3 hover:bg-indigo-50 transition w-full"
                >
                  <Image
                    src={icon}
                    alt={name}
                    width={36}
                    height={36}
                    className="object-contain"
                  />
                  <span className="text-base">{name}</span>
                </button>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default PatientSubscription;
