import React, { useCallback, useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { FaArrowLeft, FaCheck, FaHeadset } from 'react-icons/fa';
import { toast, ToastContainer, Bounce } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import {
  type CategoryId,
  CATEGORY_ORDER,
  STEPS_BY_CATEGORY,
  TOTAL_STEPS,
} from './supportPrecheckContent';

const BTN_PRIMARY =
  'w-full min-h-[52px] sm:min-h-[48px] flex items-center justify-center gap-2 py-3.5 px-4 rounded-2xl text-white text-sm font-semibold shadow-lg transition-all bg-gradient-to-r from-violet-600 via-purple-600 to-fuchsia-600 hover:from-violet-700 hover:via-purple-700 hover:to-fuchsia-700 active:scale-[0.99] focus:outline-none focus-visible:ring-2 focus-visible:ring-violet-400 focus-visible:ring-offset-2 dark:focus-visible:ring-offset-gray-900';

type Variant = 'standalone' | 'newIssue';

interface SupportPrecheckWizardProps {
  variant: Variant;
}

const SupportPrecheckWizard: React.FC<SupportPrecheckWizardProps> = ({ variant }) => {
  const navigate = useNavigate();
  const [category, setCategory] = useState<CategoryId>('power');
  const [stepIndex, setStepIndex] = useState(0);
  const [flowDone, setFlowDone] = useState(false);
  const [showReasonInput, setShowReasonInput] = useState(false);
  const [skipReason, setSkipReason] = useState('');

  const steps = STEPS_BY_CATEGORY[category];
  const step = steps[Math.min(stepIndex, steps.length - 1)];
  const stepNumber = Math.min(stepIndex + 1, TOTAL_STEPS);

  const goToNewIssueForm = useCallback(
    (state: { precheckCantCompleteReason?: string }) => {
      navigate('/support/new', {
        replace: true,
        state: {
          newIssuePrecheckDone: true,
          ...state,
        },
      });
    },
    [navigate],
  );

  const selectCategory = useCallback((id: CategoryId) => {
    setCategory(id);
    setStepIndex(0);
    setFlowDone(false);
    setShowReasonInput(false);
    setSkipReason('');
  }, []);

  const onContinue = useCallback(() => {
    if (stepIndex >= TOTAL_STEPS - 1) {
      if (variant === 'newIssue') {
        goToNewIssueForm({});
        return;
      }
      setFlowDone(true);
      return;
    }
    setStepIndex((s) => Math.min(s + 1, TOTAL_STEPS - 1));
  }, [stepIndex, variant, goToNewIssueForm]);

  const openReasonStep = useCallback(() => {
    setShowReasonInput(true);
    setSkipReason('');
  }, []);

  const cancelReasonStep = useCallback(() => {
    setShowReasonInput(false);
    setSkipReason('');
  }, []);

  const submitSkipReason = useCallback(() => {
    const trimmed = skipReason.trim();
    if (!trimmed) {
      toast.error("Please explain why you can't complete this step to continue.", {
        position: 'top-right',
        autoClose: 4000,
      });
      return;
    }
    goToNewIssueForm({ precheckCantCompleteReason: trimmed });
  }, [skipReason, goToNewIssueForm]);

  const progressDots = useMemo(
    () =>
      Array.from({ length: TOTAL_STEPS }, (_, i) => (
        <div
          key={i}
          className={
            i === stepIndex
              ? 'h-2 w-10 sm:w-12 rounded-full bg-gradient-to-r from-violet-600 to-fuchsia-500 transition-all shadow-sm'
              : 'h-2 w-2 rounded-full bg-gray-300/90 dark:bg-gray-600 transition-all'
          }
          aria-hidden
        />
      )),
    [stepIndex],
  );

  const shellClass =
    'min-h-full w-full max-w-lg mx-auto px-4 sm:px-5 py-4 sm:py-6 pb-28 sm:pb-24 bg-gradient-to-br from-violet-100/90 via-white to-fuchsia-100/80 dark:from-gray-950 dark:via-gray-900 dark:to-violet-950/50';

  return (
    <>
      <ToastContainer
        position="top-right"
        autoClose={4000}
        hideProgressBar={false}
        newestOnTop
        closeOnClick
        rtl={false}
        pauseOnFocusLoss
        draggable
        pauseOnHover
        theme="colored"
        transition={Bounce}
      />
      <div className={shellClass}>
      <div className="flex items-center gap-3 mb-6 sm:mb-8">
        <button
          type="button"
          onClick={() => navigate('/support')}
          className="text-violet-700/70 dark:text-violet-300/80 hover:text-violet-900 dark:hover:text-white p-2 -ml-2 rounded-xl min-h-[44px] min-w-[44px] flex items-center justify-center"
          aria-label="Back to support issues"
        >
          <FaArrowLeft className="text-lg" />
        </button>
        <div>
          <h1 className="text-lg sm:text-xl font-semibold text-gray-900 dark:text-white">
            {variant === 'newIssue' ? 'New issue' : 'Support'}
          </h1>
          <p className="text-xs text-violet-700/80 dark:text-violet-300/90">
            {variant === 'newIssue' ? 'Self-service checks before you create a ticket' : 'Self-service checks'}
          </p>
        </div>
      </div>

      <p className="text-[10px] sm:text-[11px] font-semibold tracking-wide text-gray-500 dark:text-gray-400 uppercase mb-3">
        What type of problem is it?
      </p>
      <div className="flex flex-wrap gap-2 mb-6 sm:mb-8">
        {CATEGORY_ORDER.map(({ id, label }) => (
          <button
            key={id}
            type="button"
            onClick={() => selectCategory(id)}
            className={`px-3.5 sm:px-4 py-2.5 rounded-2xl text-xs sm:text-sm font-medium transition-all min-h-[44px] ${
              category === id
                ? 'text-white shadow-md bg-gradient-to-r from-violet-600 to-fuchsia-600 ring-2 ring-violet-400/40'
                : 'bg-white/80 dark:bg-gray-800/90 text-gray-700 dark:text-gray-200 border border-gray-200/80 dark:border-gray-600 hover:border-violet-300 dark:hover:border-violet-500'
            }`}
          >
            {label}
          </button>
        ))}
      </div>

      {!flowDone ? (
        <>
          <div className="flex items-center justify-between gap-3 mb-3">
            <p className="text-[10px] sm:text-[11px] font-semibold tracking-wide text-gray-500 dark:text-gray-400 uppercase">
              Self-service checks
            </p>
            <p className="text-sm font-semibold bg-gradient-to-r from-violet-600 to-fuchsia-600 bg-clip-text text-transparent">
              Step {stepNumber} of {TOTAL_STEPS}
            </p>
          </div>
          <div className="flex justify-center gap-2 mb-5 sm:mb-6">{progressDots}</div>

          <div className="rounded-2xl border border-violet-200/60 dark:border-gray-700 bg-white/95 dark:bg-gray-800/95 shadow-lg shadow-violet-500/5 overflow-hidden backdrop-blur-sm">
            {step.imageSrc ? (
              <div className="bg-gray-50 dark:bg-gray-900/50">
                <img
                  src={step.imageSrc}
                  alt={step.imageCaption ?? step.title}
                  className="w-full max-h-48 sm:max-h-56 object-cover"
                  loading="lazy"
                  decoding="async"
                  referrerPolicy="no-referrer"
                  onError={(e) => {
                    e.currentTarget.style.display = 'none';
                  }}
                />
                {step.imageCaption ? (
                  <p className="text-center text-xs text-gray-500 dark:text-gray-400 py-2 px-4">
                    {step.imageCaption}
                  </p>
                ) : null}
              </div>
            ) : null}

            <div className="p-5 sm:p-6 space-y-4">
              <h2 className="text-lg sm:text-xl font-bold text-gray-900 dark:text-white leading-snug">{step.title}</h2>
              <p className="text-sm text-gray-600 dark:text-gray-300">{step.intro}</p>

              <div className="rounded-xl bg-violet-50/80 dark:bg-gray-900/60 divide-y divide-violet-100 dark:divide-gray-700 border border-violet-100/80 dark:border-gray-700">
                {step.bullets.map((text, idx) => (
                  <p key={idx} className="text-sm text-gray-700 dark:text-gray-300 p-4 leading-relaxed">
                    {text}
                  </p>
                ))}
              </div>

              <button type="button" onClick={onContinue} className={BTN_PRIMARY}>
                <span className="flex h-7 w-7 items-center justify-center rounded-full border-2 border-white/90 shrink-0">
                  <FaCheck className="text-xs" />
                </span>
                Yes, I&apos;ve tried this
              </button>

              {showReasonInput ? (
                <div
                  className="rounded-xl border border-violet-200/90 dark:border-violet-700/60 bg-gradient-to-br from-violet-50/95 via-fuchsia-50/50 to-violet-100/70 dark:from-violet-950/45 dark:via-fuchsia-950/25 dark:to-violet-900/35 p-4 sm:p-5 space-y-3 shadow-md shadow-violet-500/10"
                  role="region"
                  aria-label="Reason you cannot complete this step"
                >
                  <p className="text-sm font-bold text-gray-900 dark:text-violet-50 leading-snug">
                    Why can&apos;t you complete this step? (required to continue)
                  </p>
                  <textarea
                    value={skipReason}
                    onChange={(e) => setSkipReason(e.target.value)}
                    rows={4}
                    placeholder="e.g. No access to the panel, site policy, or missing tools…"
                    className="w-full rounded-lg border border-violet-200/90 dark:border-violet-700/70 bg-white dark:bg-gray-900 text-gray-900 dark:text-white text-sm p-3 min-h-[100px] resize-y focus:ring-2 focus:ring-violet-500 focus:border-violet-500 outline-none placeholder:text-gray-400 dark:placeholder:text-gray-500"
                  />
                  <button type="button" onClick={submitSkipReason} className={BTN_PRIMARY}>
                    Save explanation and continue
                  </button>
                  <button
                    type="button"
                    onClick={cancelReasonStep}
                    className="w-full min-h-[44px] text-center text-sm font-medium text-violet-700 dark:text-violet-300 underline underline-offset-2 hover:text-violet-900 dark:hover:text-violet-200"
                  >
                    Back to checks
                  </button>
                </div>
              ) : (
                <button
                  type="button"
                  onClick={openReasonStep}
                  className="w-full min-h-[48px] text-center text-sm font-medium text-violet-700 dark:text-violet-300 underline underline-offset-2 hover:text-violet-900 dark:hover:text-violet-200"
                >
                  I can&apos;t complete these checks
                </button>
              )}
            </div>
          </div>
        </>
      ) : (
        <div className="rounded-2xl border border-violet-200/60 dark:border-gray-700 bg-white/95 dark:bg-gray-800/95 shadow-lg p-6 text-center space-y-4">
          <p className="text-lg font-semibold text-gray-900 dark:text-white">Thanks for working through the checks</p>
          <p className="text-sm text-gray-600 dark:text-gray-300">
            If the problem is still there, create a ticket from the support issues page with what you tried.
          </p>
          <button type="button" onClick={() => navigate('/support')} className={`${BTN_PRIMARY} max-w-xs mx-auto`}>
            Go to support issues
          </button>
        </div>
      )}

      {variant === 'standalone' && !showReasonInput ? (
        <div className="mt-8 rounded-2xl bg-white/70 dark:bg-gray-800/60 border border-violet-200/50 dark:border-gray-700 p-5 flex gap-3 shadow-sm">
          <FaHeadset className="text-violet-600 dark:text-violet-400 text-xl shrink-0 mt-0.5" />
          <div>
            <p className="font-semibold text-gray-900 dark:text-white text-sm">Still need help?</p>
            <p className="text-sm text-gray-600 dark:text-gray-300 mt-1 leading-relaxed">
              To open a ticket without this checklist, use{' '}
              <button
                type="button"
                onClick={() =>
                  navigate('/support/new', { state: { newIssuePrecheckDone: true } })
                }
                className="font-medium text-violet-700 dark:text-violet-300 underline underline-offset-2 hover:text-violet-900"
              >
                Create ticket directly
              </button>{' '}
              on the{' '}
              <button
                type="button"
                onClick={() => navigate('/support')}
                className="text-violet-600 dark:text-violet-400 underline underline-offset-2"
              >
                support issues
              </button>{' '}
              page.
            </p>
          </div>
        </div>
      ) : null}
    </div>
    </>
  );
};

export default SupportPrecheckWizard;
