import React, { useState, useEffect } from 'react';
import { 
  Page, 
  Header, 
  Content, 
  InfoCard,
  Progress,
  ResponseErrorPanel,
  EmptyState,
  TabbedLayout
} from '@backstage/core-components';
import { 
  Grid, 
  Chip, 
  Typography, 
  Button, 
  Box, 
  Tabs, 
  Tab,
  Paper 
} from '@material-ui/core';
import { makeStyles } from '@material-ui/core/styles';
import { Alert } from '@material-ui/lab';
import { useAsync } from 'react-use';
import { tollgateApiRef } from '../../api/types';
import { useApi } from '@backstage/core-plugin-api';
import { SubscriptionStatus } from '../SubscriptionStatus';
import { PlanSelector } from '../PlanSelector';
import { UsageBasedPlanSelector } from '../UsageBasedPlanSelector';
import { PaymentMethodManager } from '../PaymentMethodManager';
import { InvoiceHistory } from '../InvoiceHistory';
import { UsageMetrics } from '../UsageMetrics';
import { RealTimeUsageDashboard } from '../RealTimeUsageDashboard';
import { UsageAlertsManager } from '../UsageAlertsManager';
import { BillingPeriodSummary } from '../BillingPeriodSummary';

const useStyles = makeStyles(theme => ({
  tabContent: {
    paddingTop: theme.spacing(3),
  },
}));

interface TabPanelProps {
  children?: React.ReactNode;
  index: number;
  value: number;
}

function TabPanel(props: TabPanelProps) {
  const { children, value, index, ...other } = props;
  const classes = useStyles();

  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      className={classes.tabContent}
      {...other}
    >
      {value === index && children}
    </div>
  );
}

export const TollgateDashboard = () => {
  const classes = useStyles();
  const tollgateApi = useApi(tollgateApiRef);
  const [tabValue, setTabValue] = useState(0);
  const [showDemoMode, setShowDemoMode] = useState(false);

  // Auto-enable demo mode if there are persistent API errors
  useEffect(() => {
    if (error && !showDemoMode) {
      const timer = setTimeout(() => {
        setShowDemoMode(true);
      }, 3000); // Auto-enable demo mode after 3 seconds of errors
      
      return () => clearTimeout(timer);
    }
  }, [error, showDemoMode]);

  // Safe retry function wrapper
  const safeRetry = () => {
    try {
      if (retry && typeof retry === 'function') {
        retry();
      } else {
        console.warn('Retry function not available, toggling demo mode');
        setShowDemoMode(!showDemoMode);
      }
    } catch (err) {
      console.error('Error in retry function:', err);
      setShowDemoMode(true);
    }
  };
  
  const { value: subscription, loading, error, retry } = useAsync(async () => {
    try {
      return await tollgateApi.getCurrentSubscription();
    } catch (err: any) {
      // Don't throw on 404 - just means no subscription
      if (err.message?.includes('404')) {
        return null;
      }
      // Auto-enable demo mode on other errors
      if (err.message?.includes('500') || err.message?.includes('Authentication failed')) {
        setShowDemoMode(true);
      }
      throw err;
    }
  });

  // Demo/fallback data for when backend is unavailable
  const demoSubscription = showDemoMode ? {
    id: 1,
    user_entity_ref: 'user:default/guest',
    stripe_customer_id: 'cus_demo123',
    stripe_subscription_id: 'sub_demo123',
    plan_id: 'price_demo123',
    status: 'active',
    current_period_start: new Date(Date.now() - 15 * 24 * 60 * 60 * 1000).toISOString(),
    current_period_end: new Date(Date.now() + 15 * 24 * 60 * 60 * 1000).toISOString(),
    features: ['api_access', 'analytics', 'support'],
    created_at: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString(),
    updated_at: new Date().toISOString(),
  } : null;

  const effectiveSubscription = subscription || demoSubscription;
  const isError = error && !showDemoMode;
  const isBackendUnavailable = error?.message?.includes('Failed to fetch') || 
                               error?.message?.includes('Network') ||
                               error?.message?.includes('401');

  return (
    <Page themeId="tool">
      <Header 
        title="Subscription Management" 
        subtitle="Manage your Backstage subscription and billing"
      />
      <Content>
        {/* Backend Status Alert */}
        {isBackendUnavailable && (
          <Alert 
            severity="warning" 
            action={
              <Button 
                color="inherit" 
                size="small"
                onClick={() => setShowDemoMode(!showDemoMode)}
              >
                {showDemoMode ? 'Exit Demo' : 'Demo Mode'}
              </Button>
            }
            style={{ marginBottom: 16 }}
          >
            <Typography variant="body1">
              {isError ? 'Unable to connect to subscription service' : 'Running in limited mode'}
            </Typography>
            <Typography variant="body2">
              {showDemoMode 
                ? 'Showing demo data. Some features may not work.'
                : 'Click Demo Mode to explore the interface with sample data.'}
            </Typography>
          </Alert>
        )}

        {/* Main Content */}
        {!effectiveSubscription ? (
          <Grid container spacing={3}>
            <Grid item xs={12}>
              {!isBackendUnavailable && (
                <Alert severity="info">
                  <Typography variant="h6">No Active Subscription</Typography>
                  <Typography variant="body2">
                    Select a plan below to get started with premium features.
                  </Typography>
                </Alert>
              )}
              <Box mt={3}>
                <UsageBasedPlanSelector onPlanSelected={(plan) => {
                  console.log('Plan selected:', plan);
                  safeRetry();
                }} />
              </Box>
            </Grid>
          </Grid>
        ) : (
          <Box>
            <Paper>
              <Tabs
                value={tabValue}
                onChange={(_, newValue) => setTabValue(newValue)}
                indicatorColor="primary"
                textColor="primary"
                variant="scrollable"
                scrollButtons="auto"
              >
                <Tab label="Overview" />
                <Tab label="Usage Metrics" />
                <Tab label="Real-Time Tracking" />
                <Tab label="Billing Summary" />
                <Tab label="Alerts & Limits" />
                <Tab label="Payment Methods" />
                <Tab label="Invoice History" />
              </Tabs>
            </Paper>

            <TabPanel value={tabValue} index={0}>
              <Grid container spacing={3}>
                <Grid item xs={12} md={8}>
                  <Box mb={3}>
                    <SubscriptionStatus 
                      subscription={effectiveSubscription} 
                      onUpdate={safeRetry} 
                      isDemoMode={showDemoMode}
                    />
                  </Box>
                  <BillingPeriodSummary 
                    subscription={effectiveSubscription} 
                    isDemoMode={showDemoMode}
                  />
                </Grid>
                <Grid item xs={12} md={4}>
                  <Box mb={3}>
                    <BillingOverview subscription={effectiveSubscription} />
                  </Box>
                  <Box mb={3}>
                    <QuickUsageOverview isDemoMode={showDemoMode} />
                  </Box>
                </Grid>
              </Grid>
            </TabPanel>

            <TabPanel value={tabValue} index={1}>
              <UsageMetrics refreshInterval={showDemoMode ? 60000 : 30000} />
            </TabPanel>

            <TabPanel value={tabValue} index={2}>
              <RealTimeUsageDashboard refreshInterval={showDemoMode ? 10000 : 5000} />
            </TabPanel>

            <TabPanel value={tabValue} index={3}>
              <BillingPeriodSummary 
                subscription={effectiveSubscription} 
                isDemoMode={showDemoMode}
              />
            </TabPanel>

            <TabPanel value={tabValue} index={4}>
              <UsageAlertsManager refreshInterval={showDemoMode ? 120000 : 60000} />
            </TabPanel>

            <TabPanel value={tabValue} index={5}>
              <PaymentMethodManager />
            </TabPanel>

            <TabPanel value={tabValue} index={6}>
              <InvoiceHistory />
            </TabPanel>
          </Box>
        )}
      </Content>
    </Page>
  );
};

const BillingOverview = ({ subscription }: { subscription: any }) => {
  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString();
  };

  return (
    <InfoCard title="Billing Overview">
      <Box mb={2}>
        <Typography variant="subtitle2" color="textSecondary">
          Current Plan
        </Typography>
        <Typography variant="h6">
          {subscription.plan_id}
        </Typography>
      </Box>
      
      <Box mb={2}>
        <Typography variant="subtitle2" color="textSecondary">
          Status
        </Typography>
        <Chip 
          label={subscription.status} 
          color={subscription.status === 'active' ? 'primary' : 'default'}
          size="small"
        />
      </Box>

      {subscription.current_period_end && (
        <Box mb={2}>
          <Typography variant="subtitle2" color="textSecondary">
            Next Billing Date
          </Typography>
          <Typography variant="body1">
            {formatDate(subscription.current_period_end)}
          </Typography>
        </Box>
      )}

      {subscription.trial_end && new Date(subscription.trial_end) > new Date() && (
        <Alert severity="info">
          Trial ends on {formatDate(subscription.trial_end)}
        </Alert>
      )}
    </InfoCard>
  );
};

const QuickUsageOverview = ({ isDemoMode }: { isDemoMode?: boolean }) => {
  const tollgateApi = useApi(tollgateApiRef);
  
  const { value: usageData, loading } = useAsync(async () => {
    if (isDemoMode) {
      // Return demo data
      return {
        period: {
          start: new Date(Date.now() - 15 * 24 * 60 * 60 * 1000).toISOString(),
          end: new Date(Date.now() + 15 * 24 * 60 * 60 * 1000).toISOString(),
        },
        usage: 4523,
      };
    }
    try {
      return await tollgateApi.getUsageMetrics();
    } catch (error) {
      console.error('Failed to fetch usage data:', error);
      return null;
    }
  }, [isDemoMode]);

  if (loading) {
    return (
      <InfoCard title="Usage Overview">
        <Progress />
      </InfoCard>
    );
  }

  if (!usageData) {
    return (
      <InfoCard title="Usage Overview">
        <Typography variant="body2" color="textSecondary">
          No usage data available
        </Typography>
      </InfoCard>
    );
  }

  const periodStart = new Date(usageData.period.start);
  const periodEnd = new Date(usageData.period.end);
  const daysInPeriod = Math.ceil((periodEnd.getTime() - periodStart.getTime()) / (1000 * 60 * 60 * 24));
  const daysRemaining = Math.ceil((periodEnd.getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24));
  const dailyAverage = Math.floor(usageData.usage / (daysInPeriod - daysRemaining));

  return (
    <InfoCard title="Usage Overview">
      <Box mb={2}>
        <Typography variant="subtitle2" color="textSecondary">
          Current Period Usage
        </Typography>
        <Typography variant="h6">
          {usageData.usage.toLocaleString()}
        </Typography>
      </Box>
      
      <Box mb={2}>
        <Typography variant="subtitle2" color="textSecondary">
          Daily Average
        </Typography>
        <Typography variant="body1">
          {dailyAverage.toLocaleString()} requests/day
        </Typography>
      </Box>

      <Box mb={2}>
        <Typography variant="subtitle2" color="textSecondary">
          Days Remaining
        </Typography>
        <Typography variant="body1">
          {Math.max(0, daysRemaining)} days
        </Typography>
      </Box>
    </InfoCard>
  );
};