import React, { useContext, useState } from 'react';
import { Alert, Box, Button, Card, CardContent, Divider, Stack, Typography } from '@mui/material';
import { Link as RouterLink, useNavigate } from 'react-router-dom';
import { axiosInstance } from '../../../axiosApi';
import { AuthContext } from '../../contexts/AuthContext';
import { AccountContext } from '../../contexts/AccountContext';
import { Account } from '../../data';
import TermsOfServiceDocument from '../../components/legal/TermsOfServiceDocument';
import PageWrapperLayout from '../../components/PageWrapperLayout/PageWrapperLayout';
import { AnalyticsEvents, trackEvent } from '../../utils/analytics';

type TermsOfServiceProps = {
  /** Marketing / legal alias: always read-only chrome (no app shell). */
  publicView?: boolean;
};

/**
 * Shared Terms page: public without auth; Acknowledge when signed in on /terms_of_service/.
 */
const TermsOfService = ({ publicView = false }: TermsOfServiceProps): JSX.Element => {
  const navigate = useNavigate();
  const { authenticated } = useContext(AuthContext);
  const { account, setAccount } = useContext(AccountContext);
  const [error, setError] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);

  const showAcknowledge = authenticated && !publicView;

  const handleAcknowledge = async (): Promise<void> => {
    setError(null);
    setSubmitting(true);
    try {
      await axiosInstance.post('/user/acknowledge_tos/');
      trackEvent(AnalyticsEvents.TOS_ACKNOWLEDGED);
      if (account) {
        setAccount(new Account({ ...account, has_signed_tos: true }));
      }
      navigate('/');
    } catch (err) {
      console.log(err);
      setError('Unable to acknowledge. Please try again.');
    } finally {
      setSubmitting(false);
    }
  };

  const documentBody = (
    <Card sx={{ maxWidth: 900, mx: 'auto', width: '100%' }}>
      <CardContent>
        <Typography variant="h3" component="h1" gutterBottom>
          Terms of Service
        </Typography>
        <Typography variant="subtitle1" color="text.secondary" gutterBottom>
          Hesychia · hesychia.ai · AI ML Operations, LLC
        </Typography>
      </CardContent>
      <Divider />
      <CardContent>
        <Stack spacing={1.5}>
          <TermsOfServiceDocument />
        </Stack>
      </CardContent>
      {showAcknowledge && (
        <>
          <Divider />
          <CardContent>
            {error && (
              <Alert severity="error" sx={{ mb: 2 }}>
                {error}
              </Alert>
            )}
            <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
              By clicking Acknowledge, you confirm that you have read and agree to these Terms.
            </Typography>
            <Button
              variant="contained"
              onClick={handleAcknowledge}
              disabled={submitting}
              fullWidth
            >
              {submitting ? 'Saving…' : 'Acknowledge & Agree'}
            </Button>
          </CardContent>
        </>
      )}
      {!authenticated && (
        <>
          <Divider />
          <CardContent>
            <Typography variant="body2" color="text.secondary">
              Already have an account?{' '}
              <Button component={RouterLink} to="/signin/" size="small">
                Sign in
              </Button>
            </Typography>
          </CardContent>
        </>
      )}
    </Card>
  );

  if (publicView || !authenticated) {
    return (
      <Box sx={{ py: 4, px: 2, minHeight: '100vh', bgcolor: 'background.default' }}>
        {documentBody}
      </Box>
    );
  }

  return (
    <PageWrapperLayout>
      <Box sx={{ margin: '0 auto', width: { xs: '95%', md: '80%' }, py: 2 }}>{documentBody}</Box>
    </PageWrapperLayout>
  );
};

export default TermsOfService;
