import React, { useState } from 'react';
import {
  Box,
  Typography,
  Grid,
  Button,
  Chip,
  CircularProgress,
  ToggleButtonGroup,
  ToggleButton,
  Alert,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
} from '@mui/material';
import { Elements } from '@stripe/react-stripe-js';
import { loadStripe } from '@stripe/stripe-js';
import type { StripeElementsOptions } from '@stripe/stripe-js';
import { format } from 'date-fns';
import { Card } from '../../../shared-minimal/components/Card';
import { TierCard } from '../components/TierCard';
import { PaymentMethodForm } from '../components/PaymentMethodForm';
import { BillingHistory } from '../components/BillingHistory';
import { DowngradeFlow } from '../components/DowngradeFlow';
import { DonationSection } from '../components/DonationSection';
import {
  useSubscription,
  useCheckout,
  useCancelSubscription,
  useReactivateSubscription,
  useInvoices,
  useDowngrade,
} from '../hooks/useSubscription';
import { PLANS } from '../constants/plans';
import type { BillingCycle, SubscriptionTier } from '../types/subscription.types';

const stripePromise = loadStripe(import.meta.env.VITE_STRIPE_PUBLISHABLE_KEY || '');

const paymentElementsOptions: StripeElementsOptions = {
  mode: 'setup',
  currency: 'usd',
  paymentMethodCreation: 'manual',
};

export const SubscriptionPage: React.FC = () => {
  const [billingCycle, setBillingCycle] = useState<BillingCycle>('monthly');
  const [selectedTier, setSelectedTier] = useState<SubscriptionTier | null>(null);
  const [showPaymentDialog, setShowPaymentDialog] = useState(false);
  const [showDowngradeFlow, setShowDowngradeFlow] = useState(false);
  const [downgradeTargetTier, setDowngradeTargetTier] = useState<SubscriptionTier | null>(null);

  const { data: subscriptionData, isLoading: isLoadingSubscription } = useSubscription();
  const { data: invoicesData, isLoading: isLoadingInvoices } = useInvoices();
  const checkoutMutation = useCheckout();
  const cancelMutation = useCancelSubscription();
  const reactivateMutation = useReactivateSubscription();
  const downgradeMutation = useDowngrade();

  const subscription = subscriptionData?.data;
  const invoices = invoicesData?.data || [];

  const handleBillingCycleChange = (_: React.MouseEvent<HTMLElement>, newCycle: BillingCycle | null) => {
    if (newCycle) {
      setBillingCycle(newCycle);
    }
  };

  const getTierRank = (tier: SubscriptionTier): number => {
    const ranks = { free: 0, pro: 1, enterprise: 2 };
    return ranks[tier];
  };

  const handleUpgradeClick = (tier: SubscriptionTier) => {
    const currentTier = subscription?.tier || 'free';
    const isDowngrade = getTierRank(tier) < getTierRank(currentTier);

    if (isDowngrade) {
      // Trigger downgrade flow
      setDowngradeTargetTier(tier);
      setShowDowngradeFlow(true);
    } else {
      // Trigger upgrade flow (show payment dialog)
      setSelectedTier(tier);
      setShowPaymentDialog(true);
    }
  };

  const handleDowngradeComplete = (vehicleIdsToKeep: string[]) => {
    if (!downgradeTargetTier) return;

    downgradeMutation.mutate(
      {
        targetTier: downgradeTargetTier,
        vehicleIdsToKeep,
      },
      {
        onSuccess: () => {
          setShowDowngradeFlow(false);
          setDowngradeTargetTier(null);
        },
        onError: () => {
          setShowDowngradeFlow(false);
          setDowngradeTargetTier(null);
        },
      }
    );
  };

  const handleDowngradeCancel = () => {
    setShowDowngradeFlow(false);
    setDowngradeTargetTier(null);
  };

  const handlePaymentSubmit = (paymentMethodId: string) => {
    if (!selectedTier) return;

    checkoutMutation.mutate(
      {
        tier: selectedTier,
        billingCycle,
        paymentMethodId,
      },
      {
        onSuccess: () => {
          setShowPaymentDialog(false);
          setSelectedTier(null);
        },
      }
    );
  };

  const handleCancel = () => {
    if (window.confirm('Are you sure you want to cancel your subscription? Your plan will remain active until the end of the current billing period.')) {
      cancelMutation.mutate();
    }
  };

  const handleReactivate = () => {
    reactivateMutation.mutate();
  };

  if (isLoadingSubscription) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: '400px' }}>
        <CircularProgress />
      </Box>
    );
  }

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'active':
        return 'success';
      case 'past_due':
        return 'warning';
      case 'canceled':
        return 'error';
      default:
        return 'default';
    }
  };

  return (
    <Box sx={{ p: 3 }}>
      <Typography variant="h4" gutterBottom fontWeight="bold">
        Subscription
      </Typography>

      {subscription && (
        <Card padding="lg" className="mb-6">
          <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
            <Box>
              <Box sx={{ display: 'flex', gap: 1, mb: 2 }}>
                <Chip
                  label={subscription.tier.toUpperCase()}
                  color="primary"
                  size="small"
                />
                <Chip
                  label={subscription.status}
                  color={getStatusColor(subscription.status)}
                  size="small"
                />
              </Box>

              <Typography variant="h6" gutterBottom>
                Current Plan: {PLANS.find((p) => p.tier === subscription.tier)?.name || subscription.tier}
              </Typography>

              {subscription.currentPeriodEnd && (
                <Typography variant="body2" color="text.secondary" gutterBottom>
                  Next billing date: {format(new Date(subscription.currentPeriodEnd), 'MMM dd, yyyy')}
                </Typography>
              )}

              {subscription.cancelAtPeriodEnd && (
                <Alert severity="warning" sx={{ mt: 2 }}>
                  Your subscription will be canceled at the end of the current billing period.
                </Alert>
              )}
            </Box>

            <Box>
              {subscription.cancelAtPeriodEnd ? (
                <Button
                  variant="outlined"
                  color="primary"
                  onClick={handleReactivate}
                  disabled={reactivateMutation.isPending}
                >
                  Reactivate
                </Button>
              ) : subscription.tier !== 'free' ? (
                <Button
                  variant="outlined"
                  color="error"
                  onClick={handleCancel}
                  disabled={cancelMutation.isPending}
                >
                  Cancel Subscription
                </Button>
              ) : null}
            </Box>
          </Box>
        </Card>
      )}

      <Card padding="lg" className="mb-6">
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
          <Typography variant="h6" fontWeight="bold">
            Available Plans
          </Typography>

          <ToggleButtonGroup
            value={billingCycle}
            exclusive
            onChange={handleBillingCycleChange}
            size="small"
          >
            <ToggleButton value="monthly">Monthly</ToggleButton>
            <ToggleButton value="yearly">Yearly</ToggleButton>
          </ToggleButtonGroup>
        </Box>

        <Grid container spacing={3}>
          {PLANS.map((plan) => (
            <Grid item xs={12} md={4} key={plan.tier}>
              <TierCard
                plan={plan}
                billingCycle={billingCycle}
                currentTier={subscription?.tier}
                isLoading={checkoutMutation.isPending}
                onUpgrade={() => handleUpgradeClick(plan.tier)}
              />
            </Grid>
          ))}
        </Grid>
      </Card>

      <Card padding="lg" className="mb-6">
        <Typography variant="h6" fontWeight="bold" gutterBottom>
          Billing History
        </Typography>

        {isLoadingInvoices ? (
          <Box sx={{ display: 'flex', justifyContent: 'center', p: 3 }}>
            <CircularProgress />
          </Box>
        ) : (
          <BillingHistory invoices={invoices} />
        )}
      </Card>

      <Elements stripe={stripePromise}>
        <DonationSection currentTier={subscription?.tier} />
      </Elements>

      <Dialog
        open={showPaymentDialog}
        onClose={() => !checkoutMutation.isPending && setShowPaymentDialog(false)}
        maxWidth="sm"
        fullWidth
      >
        <DialogTitle>
          Upgrade to {selectedTier && PLANS.find((p) => p.tier === selectedTier)?.name}
        </DialogTitle>
        <DialogContent>
          <Elements stripe={stripePromise} options={paymentElementsOptions}>
            <PaymentMethodForm
              onSubmit={handlePaymentSubmit}
              isLoading={checkoutMutation.isPending}
            />
          </Elements>
        </DialogContent>
        <DialogActions>
          <Button
            onClick={() => setShowPaymentDialog(false)}
            disabled={checkoutMutation.isPending}
          >
            Cancel
          </Button>
        </DialogActions>
      </Dialog>

      {showDowngradeFlow && downgradeTargetTier && (
        <DowngradeFlow
          targetTier={downgradeTargetTier}
          onComplete={handleDowngradeComplete}
          onCancel={handleDowngradeCancel}
        />
      )}
    </Box>
  );
};
