import * as icon from '@mdi/js';
import Head from 'next/head';
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import type { ReactElement } from 'react';
import LayoutAuthenticated from '../layouts/Authenticated';
import SectionMain from '../components/SectionMain';
import SectionTitleLineWithButton from '../components/SectionTitleLineWithButton';
import CardBox from '../components/CardBox';
import BaseButton from '../components/BaseButton';
import BaseIcon from '../components/BaseIcon';
import { getPageTitle } from '../config';
import { useAppSelector } from '../stores/hooks';
import moment from 'moment';

const PlanCard = ({ plan, currentPlanId, onUpgrade }: any) => {
  const isCurrent = plan.id === currentPlanId;

  return (
    <CardBox className={`h-full flex flex-col ${isCurrent ? 'border-2 border-blue-500 ring-2 ring-blue-500 ring-opacity-10' : ''}`}>
      <div className="flex-grow">
        <div className="flex justify-between items-center mb-4">
          <h3 className="text-xl font-bold">{plan.name}</h3>
          {isCurrent && (
            <span className="text-xs bg-blue-100 text-blue-600 px-2 py-1 rounded-full font-bold">CURRENT PLAN</span>
          )}
        </div>
        <div className="mb-6">
          <span className="text-4xl font-black">${plan.price}</span>
          <span className="text-gray-500">/mo</span>
        </div>
        <ul className="space-y-3 mb-8">
          {plan.features?.map((feature: string, i: number) => (
            <li key={i} className="flex items-center text-sm">
              <BaseIcon path={icon.mdiCheckCircle} size={18} className="text-emerald-500 mr-2" />
              {feature}
            </li>
          ))}
        </ul>
      </div>
      <BaseButton
        label={isCurrent ? 'Current Plan' : `Upgrade to ${plan.name}`}
        color={isCurrent ? 'whiteDark' : 'info'}
        disabled={isCurrent}
        className="w-full mt-auto"
        onClick={() => onUpgrade(plan)}
      />
    </CardBox>
  );
};

const BillingPage = () => {
  const { currentUser } = useAppSelector((state) => state.auth);
  const [plans, setPlans] = useState([]);
  const [business, setBusiness] = useState<any>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const [plansRes, metricsRes] = await Promise.all([
          axios.get('/dashboard/business-metrics'), // reusing for business data
          // We need a plans endpoint, but since I seeded them, I can mock or create one
        ]);
        
        // Mocking plans for now based on migration seeds if no endpoint exists
        setPlans([
          {
            id: '00000000-0000-0000-0000-000000000001',
            name: 'Basic (Free)',
            price: 0,
            features: ['Limited Leads', 'Standard Listing'],
          },
          {
            id: '00000000-0000-0000-0000-000000000002',
            name: 'Professional',
            price: 49.99,
            features: ['Unlimited Leads', 'Priority Support', 'Enhanced Profile'],
          },
          {
            id: '00000000-0000-0000-0000-000000000003',
            name: 'Enterprise',
            price: 199.99,
            features: ['Custom Branding', 'API Access', 'Dedicated Manager'],
          },
        ] as any);

        if (metricsRes.data.businesses?.length) {
          setBusiness(metricsRes.data.businesses[0]);
        }
      } catch (err) {
        console.error('Failed to fetch billing data', err);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, []);

  const handleUpgrade = (plan: any) => {
    alert(`Upgrading to ${plan.name}. This would normally trigger a payment flow.`);
  };

  if (loading) {
    return (
      <SectionMain>
        <div className="flex items-center justify-center h-64">
          <BaseIcon path={icon.mdiLoading} size={48} className="animate-spin text-gray-400" />
        </div>
      </SectionMain>
    );
  }

  return (
    <>
      <Head>
        <title>{getPageTitle('Billing & Plans')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={icon.mdiCreditCardOutline} title="Billing & Plans" main />

        {business && (
          <div className="mb-8 p-6 bg-white dark:bg-slate-900 rounded-2xl shadow-sm border border-gray-100 dark:border-slate-800 flex flex-col md:flex-row justify-between items-center">
            <div>
              <div className="text-gray-500 text-sm mb-1 uppercase tracking-wider font-bold">Current Plan</div>
              <div className="text-2xl font-black">{business.plan?.name || 'Basic'}</div>
              <div className="text-gray-500 text-sm mt-2">
                Your plan renews on <span className="font-bold text-gray-900 dark:text-white">{moment(business.renewal_date).format('MMMM D, YYYY')}</span>
              </div>
            </div>
            <div className="mt-4 md:mt-0 flex space-x-2">
               <BaseButton label="View Invoices" color="white" small />
               <BaseButton label="Payment Method" color="white" small />
            </div>
          </div>
        )}

        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
          {plans.map((plan: any) => (
            <PlanCard
              key={plan.id}
              plan={plan}
              currentPlanId={business?.planId}
              onUpgrade={handleUpgrade}
            />
          ))}
        </div>

        <CardBox className="mt-12 bg-gray-50 dark:bg-slate-800 border-dashed">
           <div className="flex items-center p-4">
              <div className="bg-blue-100 p-3 rounded-full mr-4">
                <BaseIcon path={icon.mdiInformation} size={24} className="text-blue-500" />
              </div>
              <div>
                <h4 className="font-bold">Need a custom plan?</h4>
                <p className="text-sm text-gray-500">Contact our sales team for enterprise solutions tailored to your specific needs.</p>
              </div>
              <BaseButton label="Contact Sales" color="light" className="ml-auto" />
           </div>
        </CardBox>
      </SectionMain>
    </>
  );
};

BillingPage.getLayout = function getLayout(page: ReactElement) {
  return <LayoutAuthenticated>{page}</LayoutAuthenticated>;
};

export default BillingPage;
