import React from 'react';
import Box from '@mui/material/Box';
import Card from '@mui/material/Card';
import type { SxProps, Theme } from '@mui/material/styles';
import { keyframes } from '@mui/material/styles';
import { WizardLayout } from '../../templates/WizardLayout';
import { Typography } from '../../atoms/Typography';
import { Button } from '../../atoms/Button';
import { Divider } from '../../atoms/Divider';
import { Link } from '../../atoms/Link';

// ─── Animated tick ──────────────────────────────────────────────────────────

const scaleIn = keyframes`
  0%   { transform: scale(0.85); opacity: 0; }
  60%  { transform: scale(1.04); opacity: 1; }
  100% { transform: scale(1); opacity: 1; }
`;

/** Animated success tick — circle draws, then checkmark appears */
const AnimatedTick: React.FC<{ size?: number }> = ({ size = 80 }) => (
  <Box
    sx={{
      width: size,
      height: size,
      animation: `${scaleIn} 0.6s ease-out both`,
      '@keyframes drawCircle': {
        from: { strokeDashoffset: 251 },
        to: { strokeDashoffset: 0 },
      },
      '@keyframes drawCheck': {
        from: { strokeDashoffset: 60 },
        to: { strokeDashoffset: 0 },
      },
      '& circle': {
        strokeDasharray: 251,
        strokeDashoffset: 251,
        animation: 'drawCircle 0.7s ease-out 0.2s forwards',
      },
      '& polyline': {
        strokeDasharray: 60,
        strokeDashoffset: 60,
        animation: 'drawCheck 0.4s ease-out 0.8s forwards',
      },
    }}
  >
    <svg viewBox="0 0 100 100" width={size} height={size} fill="none">
      <circle
        cx="50"
        cy="50"
        r="40"
        stroke="var(--fa-color-brand-400)"
        strokeWidth="4"
        strokeLinecap="round"
      />
      <polyline
        points="32,52 45,65 68,38"
        stroke="var(--fa-color-brand-500)"
        strokeWidth="5"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  </Box>
);

// ─── Types ───────────────────────────────────────────────────────────────────

/** Next step link shown on the confirmation page */
export interface ConfirmationLink {
  label: string;
  href?: string;
  onClick?: () => void;
}

/** Props for the ConfirmationStep page component */
export interface ConfirmationStepProps {
  /** Whether this is a pre-planning flow (different copy) */
  isPrePlanning?: boolean;
  /** User's email address (shown in confirmation text) */
  email?: string;
  /** User's phone number (shown in at-need confirmation) */
  phone?: string;
  /** Expected callback timeframe (at-need) */
  callbackTimeframe?: string;
  /** Business contact phone number for making changes */
  contactPhone?: string;
  /** Navigation links to next steps */
  nextSteps?: ConfirmationLink[];
  /** Callback for "View your plan" */
  onViewPlan?: () => void;
  /** Navigation bar */
  navigation?: React.ReactNode;
  /** Hide the help bar */
  hideHelpBar?: boolean;
  /** MUI sx prop */
  sx?: SxProps<Theme>;
}

// ─── Component ───────────────────────────────────────────────────────────────

/**
 * Step 15 — Confirmation / Plan View for the FA arrangement wizard.
 *
 * Terminal confirmation page. Different copy for at-need vs pre-planning.
 * Confirming and orienting — not celebratory.
 *
 * At-need: "Your arrangement has been submitted" + callback info
 * Pre-planning: "Your plan has been saved" + return-anytime info
 *
 * No progress indicator. No back button. Links to post-plan flows.
 *
 * Pure presentation component — props in, callbacks out.
 *
 * Spec: documentation/steps/steps/15_view.yaml
 */
export const ConfirmationStep: React.FC<ConfirmationStepProps> = ({
  isPrePlanning = false,
  email,
  phone,
  callbackTimeframe = 'within 2 hours',
  contactPhone = '1800 987 888',
  nextSteps = [],
  onViewPlan,
  navigation,
  hideHelpBar,
  sx,
}) => {
  return (
    <WizardLayout variant="centered-form" navigation={navigation} hideHelpBar={hideHelpBar} sx={sx}>
      <Box sx={{ textAlign: 'center', py: { xs: 4, md: 6 } }}>
        {/* Animated success tick */}
        <Box sx={{ display: 'flex', justifyContent: 'center', mb: 3 }}>
          <AnimatedTick size={80} />
        </Box>

        {/* Heading */}
        <Typography variant="display3" component="h1" sx={{ mb: 2 }} tabIndex={-1}>
          {isPrePlanning ? 'Your plan has been saved' : 'Your arrangement has been submitted'}
        </Typography>

        {/* Brief reassurance line */}
        <Typography
          variant="body1"
          color="text.secondary"
          sx={{ mb: 4, maxWidth: 480, mx: 'auto' }}
        >
          {isPrePlanning
            ? 'Everything is safely stored. You can come back and update it anytime.'
            : `We've received your arrangement and someone will be in touch shortly.`}
        </Typography>

        {/* What happens next — warm card */}
        <Card
          variant="outlined"
          sx={{
            textAlign: 'left',
            p: { xs: 3, md: 4 },
            mb: 4,
            maxWidth: 560,
            mx: 'auto',
            bgcolor: 'var(--fa-color-surface-warm)',
            borderColor: 'var(--fa-color-brand-200)',
          }}
        >
          <Typography variant="h5" sx={{ mb: 2 }}>
            What happens next
          </Typography>

          {isPrePlanning ? (
            <Box
              component="ul"
              sx={{ m: 0, pl: 2.5, display: 'flex', flexDirection: 'column', gap: 1.5 }}
            >
              {email && (
                <Typography component="li" variant="body2" color="text.secondary">
                  We&apos;ve sent a copy of your plan to <strong>{email}</strong>
                </Typography>
              )}
              <Typography component="li" variant="body2" color="text.secondary">
                You can return and make changes at any time — your plan will be here
              </Typography>
              <Typography component="li" variant="body2" color="text.secondary">
                When the time comes, your family can contact us and we&apos;ll have everything ready
              </Typography>
            </Box>
          ) : (
            <Box
              component="ul"
              sx={{ m: 0, pl: 2.5, display: 'flex', flexDirection: 'column', gap: 1.5 }}
            >
              <Typography component="li" variant="body2" color="text.secondary">
                A funeral arranger will call you
                {phone && (
                  <>
                    {' '}
                    on <strong>{phone}</strong>
                  </>
                )}{' '}
                {callbackTimeframe} to confirm the details
              </Typography>
              {email && (
                <Typography component="li" variant="body2" color="text.secondary">
                  A confirmation has been sent to <strong>{email}</strong>
                </Typography>
              )}
              <Typography component="li" variant="body2" color="text.secondary">
                Need to make changes before then? Call us on{' '}
                <Link href={`tel:${contactPhone.replace(/\s/g, '')}`} underline="always">
                  {contactPhone}
                </Link>
              </Typography>
            </Box>
          )}
        </Card>

        {/* Primary CTA */}
        {onViewPlan && (
          <Button variant="contained" size="large" onClick={onViewPlan} sx={{ mb: 2 }}>
            View your plan
          </Button>
        )}

        {/* Secondary links */}
        {nextSteps.length > 0 && (
          <>
            <Divider sx={{ my: 3, maxWidth: 480, mx: 'auto' }} />
            <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1, alignItems: 'center' }}>
              {nextSteps.map((link) => (
                <Link
                  key={link.label}
                  href={link.href || '#'}
                  onClick={
                    link.onClick
                      ? (e: React.MouseEvent) => {
                          e.preventDefault();
                          link.onClick?.();
                        }
                      : undefined
                  }
                  underline="hover"
                  sx={{ fontWeight: 500 }}
                >
                  {link.label}
                </Link>
              ))}
            </Box>
          </>
        )}
      </Box>
    </WizardLayout>
  );
};

ConfirmationStep.displayName = 'ConfirmationStep';
export default ConfirmationStep;
