'use client';

import { useEffect, useMemo, useState } from 'react';
import { Modal } from '@/components/ui/modal';
import { Typography } from '@/components/atoms/typogrpahy';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import { useAddToHomeTutorial } from '../hooks/useAddToHomeTutorial';

interface AddToHomeTutorialModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSkip?: () => void;
  onDone?: () => void;
}

export const AddToHomeTutorialModal: React.FC<AddToHomeTutorialModalProps> = ({
  isOpen,
  onClose,
  onSkip,
  onDone,
}) => {
  const tutorial = useAddToHomeTutorial();
  const totalSteps = tutorial.steps.length;
  const [currentStep, setCurrentStep] = useState(0);
  const [mediaError, setMediaError] = useState(false);

  useEffect(() => {
    if (!isOpen) return;
    setCurrentStep(0);
    setMediaError(false);
  }, [isOpen, tutorial.key]);

  useEffect(() => {
    setMediaError(false);
  }, [currentStep, tutorial.key]);

  const step = tutorial.steps[currentStep];

  const stepLabel = useMemo(() => {
    if (totalSteps <= 1) return '';
    const index = Math.min(Math.max(currentStep + 1, 1), totalSteps);
    return `Step ${index} of ${totalSteps}`;
  }, [currentStep, totalSteps]);

  const handlePrev = () => setCurrentStep((prev) => Math.max(prev - 1, 0));
  const handleNext = () => setCurrentStep((prev) => Math.min(prev + 1, totalSteps - 1));

  if (!isOpen) return null;

  return (
    <Modal
      isOpen={isOpen}
      onClose={onClose}
      showCloseButton={false}
      className="mx-4 w-[92vw] max-w-2xl max-h-[85vh] overflow-hidden"
    >
      <div className="flex max-h-[85vh] flex-col">
        <div className="flex-1 overflow-y-auto p-4 sm:p-6">
        <div className="flex flex-wrap items-center justify-between gap-3">
          <Typography variant="h5" className="text-gray-900 dark:text-white">
            Add Webapp to Home Screen
          </Typography>
          <span className="inline-flex items-center rounded-full bg-brand-50 px-3 py-1 text-xs font-semibold text-brand-700">
            {tutorial.label}
          </span>
        </div>

        <div className="mt-4 space-y-3">
          <Typography variant="b4" className="text-gray-600 dark:text-gray-300">
            {step.description}
          </Typography>
        </div>

        <div className="mt-4">
          <div className="relative overflow-hidden rounded-2xl border border-gray-200 bg-gray-50">
            <div className="flex w-full items-center justify-center">
              {mediaError ? (
                <div className="flex h-full w-full items-center justify-center text-sm text-gray-500">
                  Tutorial media not available yet.
                </div>
              ) : step.media.type === 'video' ? (
                <video
                  className="w-full max-h-[50vh] object-contain"
                  playsInline
                  autoPlay
                  loop
                  muted
                  controls={false}
                  poster={step.media.poster}
                  onPause={(event) => {
                    event.currentTarget.play().catch(() => undefined);
                  }}
                  onError={() => setMediaError(true)}
                >
                  <source src={step.media.src} />
                </video>
              ) : (
                <img
                  src={step.media.src}
                  alt={step.media.alt}
                  className="w-full max-h-[50vh] object-contain"
                  loading="eager"
                  onError={() => setMediaError(true)}
                />
              )}
            </div>
          </div>
        </div>

        </div>

        <div className="sticky bottom-0 z-10 w-full bg-white/95 px-4 py-2 backdrop-blur sm:px-6">
          <div className="flex flex-wrap items-center justify-end gap-3">
            {currentStep > 0 && (
              <button
                type="button"
                onClick={handlePrev}
                className="inline-flex min-w-[120px] items-center justify-center gap-2 rounded-full border border-gray-200 px-4 py-2 text-sm font-semibold text-gray-700 transition-colors hover:bg-gray-50"
                aria-label="Previous step"
              >
                <ChevronLeft className="h-4 w-4" />
                Back
              </button>
            )}

            <button
              type="button"
              onClick={currentStep === totalSteps - 1 ? (onDone ?? onClose) : handleNext}
              className="inline-flex min-w-[120px] items-center justify-center gap-2 rounded-full bg-brand-600 px-4 py-2 text-sm font-semibold text-white transition-colors hover:bg-brand-700"
              aria-label={currentStep === totalSteps - 1 ? 'Done' : 'Continue'}
            >
              {currentStep === totalSteps - 1 ? 'Done' : 'Continue'}
              {currentStep !== totalSteps - 1 && <ChevronRight className="h-4 w-4" />}
            </button>
          </div>

          <div className="mt-3 h-px w-full bg-gray-100" />

          <div className="mt-3 text-center text-sm text-gray-500">
            Don't want to add now?{' '}
            <button
              type="button"
              onClick={onSkip ?? onClose}
              className="font-medium text-gray-700 underline-offset-2 underline"
            >
              Remind me tomorrow
            </button>
          </div>
        </div>
      </div>
    </Modal>
  );
};
