import React, { useContext, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import styled from 'styled-components';
import { applyAccessToken, axiosInstance } from '../../../axiosApi';
import { clearTokens, getRefreshToken } from '../../auth/tokenStorage';
import { AccountContext } from '../../contexts/AccountContext';
import { AuthContext } from '../../contexts/AuthContext';
import { AnalyticsEvents, trackEvent } from '../../utils/analytics';
import { logOutRevenueCat } from '../../utils/revenueCat';

const GlassCard = styled.div`
  background: ${({ theme }) => theme.colors.cardBackground};
  backdrop-filter: blur(10px);
  border: 1px solid ${({ theme }) => theme.colors.cardBorder};
  border-radius: 1rem;
  padding: 2rem;
  width: 100%;
  max-width: 1000px;
  margin-bottom: 2rem;
  box-shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.37);
`;

const CardTitle = styled.h2`
  font-size: 1.8rem;
  margin-bottom: 1rem;
  color: ${({ theme }) => theme.colors.text};
  border-bottom: 1px solid ${({ theme }) => theme.colors.cardBorder};
  padding-bottom: 1rem;
`;

const BodyText = styled.p`
  color: ${({ theme }) => theme.colors.text};
  opacity: 0.75;
  margin: 0 0 1rem 0;
  line-height: 1.5;
`;

const ErrorText = styled.p`
  color: #ff6b6b;
  margin: 0.75rem 0 0 0;
  font-size: 0.95rem;
`;

const ButtonRow = styled.div`
  display: flex;
  flex-wrap: wrap;
  gap: 0.75rem;
  margin-top: 1rem;
`;

const DangerButton = styled.button`
  background: transparent;
  border: 1px solid #ff6b6b;
  border-radius: 0.5rem;
  color: #ff6b6b;
  padding: 0.8rem 1.5rem;
  font-weight: 600;
  cursor: pointer;

  &:hover {
    background: #ff6b6b22;
  }

  &:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }
`;

const SecondaryButton = styled.button`
  background: transparent;
  border: 1px solid ${({ theme }) => theme.colors.cardBorder};
  border-radius: 0.5rem;
  color: ${({ theme }) => theme.colors.text};
  padding: 0.8rem 1.5rem;
  font-weight: 600;
  cursor: pointer;

  &:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }
`;

const ConfirmInput = styled.input`
  width: 100%;
  max-width: 420px;
  background: ${({ theme }) =>
    theme.darkMode ? 'rgba(255, 255, 255, 0.05)' : 'rgba(0, 0, 0, 0.05)'};
  border: 1px solid ${({ theme }) => theme.colors.cardBorder};
  border-radius: 0.5rem;
  padding: 0.8rem;
  color: ${({ theme }) => theme.colors.text};
  font-size: 1rem;
  outline: none;
  margin-top: 0.5rem;

  &:focus {
    border-color: #ff6b6b;
  }
`;

const ModalBackdrop = styled.div`
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.55);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 1.5rem;
`;

const ModalCard = styled.div`
  background: ${({ theme }) => theme.colors.cardBackground};
  backdrop-filter: blur(12px);
  border: 1px solid ${({ theme }) => theme.colors.cardBorder};
  border-radius: 1rem;
  padding: 1.75rem;
  max-width: 520px;
  width: 100%;
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.45);
`;

const ModalTitle = styled.h3`
  margin: 0 0 0.75rem 0;
  color: ${({ theme }) => theme.colors.text};
  font-size: 1.35rem;
`;

function apiErrorMessage(error: unknown, fallback: string): string {
  const axiosError = error as {
    response?: { data?: { detail?: string } };
    message?: string;
  };
  return axiosError.response?.data?.detail || axiosError.message || fallback;
}

const DeleteAccountSection = (): JSX.Element => {
  const { account, setAccount } = useContext(AccountContext);
  const { setAuthentication } = useContext(AuthContext);
  const navigate = useNavigate();
  const [confirmOpen, setConfirmOpen] = useState(false);
  const [confirmEmail, setConfirmEmail] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const email = account?.email || '';

  const closeModal = () => {
    if (loading) return;
    setConfirmOpen(false);
    setConfirmEmail('');
    setError('');
  };

  const handleDelete = async () => {
    if (!email || confirmEmail.trim().toLowerCase() !== email.toLowerCase()) {
      setError('Type your account email exactly to confirm.');
      return;
    }

    setLoading(true);
    setError('');
    trackEvent(AnalyticsEvents.ACCOUNT_DELETE_STARTED);

    try {
      const refreshToken = getRefreshToken();
      await axiosInstance.delete('/user/', {
        data: refreshToken ? { refresh_token: refreshToken } : {},
      });
      trackEvent(AnalyticsEvents.ACCOUNT_DELETE_SUCCESS);
      try {
        if (refreshToken) {
          await axiosInstance.post('blacklist/', { refresh_token: refreshToken });
        }
      } catch {
        // Account already deleted; local cleanup is enough.
      }
      await clearTokens();
      applyAccessToken(null);
      setAuthentication(false);
      setAccount(undefined);
      void Promise.resolve(logOutRevenueCat()).catch((err) => console.warn('RevenueCat logOut', err));
      navigate('/signin/');
    } catch (err: unknown) {
      trackEvent(AnalyticsEvents.ACCOUNT_DELETE_FAILED);
      setError(apiErrorMessage(err, 'Could not delete account. Try again.'));
      setLoading(false);
    }
  };

  return (
    <>
      <GlassCard data-testid="delete-account-section">
        <CardTitle>Delete account</CardTitle>
        <BodyText>
          Permanently deactivate your account. Conversations are hidden and you will
          be signed out. This cannot be undone from the app.
        </BodyText>
        <DangerButton type="button" onClick={() => setConfirmOpen(true)}>
          Delete my account
        </DangerButton>
      </GlassCard>

      {confirmOpen ? (
        <ModalBackdrop
          role="presentation"
          onClick={closeModal}
          data-testid="delete-account-modal"
        >
          <ModalCard
            role="dialog"
            aria-modal="true"
            aria-labelledby="delete-account-title"
            onClick={(event) => event.stopPropagation()}
          >
            <ModalTitle id="delete-account-title">Delete your account?</ModalTitle>
            <BodyText>
              Type <strong>{email || 'your email'}</strong> to confirm. You will lose
              access immediately after deletion.
            </BodyText>
            <ConfirmInput
              type="email"
              autoComplete="off"
              placeholder="Confirm email"
              value={confirmEmail}
              onChange={(event) => setConfirmEmail(event.target.value)}
              disabled={loading}
              aria-label="Confirm email"
            />
            {error ? <ErrorText role="alert">{error}</ErrorText> : null}
            <ButtonRow>
              <DangerButton
                type="button"
                onClick={handleDelete}
                disabled={loading || !confirmEmail}
              >
                {loading ? 'Deleting…' : 'Delete account'}
              </DangerButton>
              <SecondaryButton type="button" onClick={closeModal} disabled={loading}>
                Keep account
              </SecondaryButton>
            </ButtonRow>
          </ModalCard>
        </ModalBackdrop>
      ) : null}
    </>
  );
};

export default DeleteAccountSection;
