'use client';

import { useEffect, useRef, useState } from 'react';

import { useTranslations } from 'next-intl';

import { zodResolver } from '@hookform/resolvers/zod';
import {
  Calendar,
  CheckCircle,
  ChevronLeft,
  ChevronRight,
  FileText,
  Send,
  Users,
} from 'lucide-react';
import { useForm } from 'react-hook-form';

import TurnstileWidget from '@/components/TurnstileWidget';
import { Button } from '@/components/ui/button';
import { useToast } from '@/hooks/use-toast';
import { EventFormValues, eventSubmitFormSchema } from '@/lib/schemas/eventSubmitFormSchema';

import { InstitutionListItem } from '@/types/Institutions';

import { Link } from '@/i18n/navigation';

import StepCreators from './steps/StepCreators';
import StepDateAndLocation from './steps/StepDateAndLocation';
import StepDetailsAndCategory from './steps/StepDetailsAndCategory';
import StepSuccess from './steps/StepSuccess';

interface MultiStepEventSubmitFormProps {
  institutionList: InstitutionListItem[];
  categories: { id: number; name: string }[];
}

const getSteps = (t: (key: string) => string) => [
  {
    id: 1,
    label: t('steps.creators'),
    shortLabel: t('steps.creatorsShort'),
    icon: Users,
    color: 'from-mma-blue to-mma-blue/80',
  },
  {
    id: 2,
    label: t('steps.dateAndLocation'),
    shortLabel: t('steps.dateAndLocationShort'),
    icon: Calendar,
    color: 'from-mma-cyan to-mma-cyan/80',
  },
  {
    id: 3,
    label: t('steps.details'),
    shortLabel: t('steps.detailsShort'),
    icon: FileText,
    color: 'from-mma-blue/80 to-mma-cyan',
  },
  {
    id: 4,
    label: t('steps.success'),
    shortLabel: t('steps.successShort'),
    icon: CheckCircle,
    color: 'from-green-500 to-green-400',
  },
];

export default function MultiStepEventSubmitForm({
  institutionList,
  categories,
}: MultiStepEventSubmitFormProps) {
  const t = useTranslations('eventSubmit');
  const { toast } = useToast();
  const [currentStep, setCurrentStep] = useState(1);
  const [completedSteps, setCompletedSteps] = useState<number[]>([]);
  const [turnstileToken, setTurnstileToken] = useState('');
  const STEPS = getSteps(t);
  const activeStep = STEPS.find((step) => step.id === currentStep);
  const progressPercent = Math.min(100, Math.round((currentStep / STEPS.length) * 100));
  const formTopRef = useRef<HTMLDivElement>(null);

  const form = useForm<EventFormValues>({
    resolver: zodResolver(eventSubmitFormSchema),
    defaultValues: {
      startDate: '',
      startTime: '',
      endDate: '',
      endTime: '',
      eventName: '',
      description: '',
      infoUrl: '',
      ticketUrl: '',
      customLocation: '',
      notes: '',
      useCustomLocation: false,
      isMultiDay: false,
      selectedInstitution: undefined,
      eventCategory: undefined,
      customRadioInput: '',
      selectedType: undefined,
      selectedSubtype: undefined,
      selectedCreators: [],
      selectedCreatorsObjects: [],
      otherCreators: '',
      uploadedImages: [],
    },
    mode: 'onChange',
  });

  const {
    control,
    handleSubmit,
    formState: { errors, isSubmitting },
    reset,
    watch,
    setValue,
    trigger,
  } = form;

  // Scroll to top when step changes
  useEffect(() => {
    if (formTopRef.current) {
      formTopRef.current.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
  }, [currentStep]);

  const validateStep = async (step: number): Promise<boolean> => {
    let fieldsToValidate: (keyof EventFormValues)[] = [];

    if (step === 1) {
      // Creators
      fieldsToValidate = ['selectedCreators', 'otherCreators'];
    } else if (step === 2) {
      // Date and Location
      fieldsToValidate = ['startDate', 'selectedInstitution', 'customLocation'];
    } else if (step === 3) {
      // Details and Categories
      fieldsToValidate = ['eventName', 'description', 'eventCategory'];
    }
    // Step 4 is success screen, no validation needed

    return await trigger(fieldsToValidate);
  };

  const nextStep = async () => {
    // Step 3-nál submitoljuk a formot
    if (currentStep === 3) {
      // Validáljuk az ÖSSZES lépést submit előtt
      const step1Valid = await validateStep(1);
      const step2Valid = await validateStep(2);
      const step3Valid = await validateStep(3);

      // console.log("Validation results:", {
      //   step1Valid,
      //   step2Valid,
      //   step3Valid,
      //   errors,
      //   formValues: watch(),
      // });

      if (!step1Valid) {
        // Ha step 1 hibás, ugorjunk oda
        setCurrentStep(1);
        toast({
          variant: 'destructive',
          title: t('errors.validationError'),
          description: t('errors.step1ValidationError'),
        });
        return;
      }

      if (!step2Valid) {
        // Ha step 2 hibás, ugorjunk oda
        setCurrentStep(2);
        toast({
          variant: 'destructive',
          title: t('errors.validationError'),
          description: t('errors.step2ValidationError'),
        });
        return;
      }

      if (!step3Valid) {
        console.error('Step 3 validation failed:', errors);
        toast({
          variant: 'destructive',
          title: t('errors.validationError'),
          description: t('errors.step3ValidationError'),
        });
        return;
      }

      if (!turnstileToken) {
        toast({
          variant: 'destructive',
          title: t('errors.validationError'),
          description: 'Kérlek igazold, hogy nem vagy robot.',
        });
        return;
      }

      // Ha minden valid, submitoljuk
      await handleSubmit(onSubmit)();
    } else {
      const isValid = await validateStep(currentStep);
      if (isValid) {
        // Jelöljük meg az aktuális lépést befejezettként
        if (!completedSteps.includes(currentStep)) {
          setCompletedSteps([...completedSteps, currentStep]);
        }
        if (currentStep < STEPS.length) {
          setCurrentStep(currentStep + 1);
        }
      }
    }
  };

  const prevStep = () => {
    if (currentStep > 1) {
      setCurrentStep(currentStep - 1);
    }
  };

  const onSubmit = async (values: EventFormValues) => {
    const kezdete = values.startTime
      ? `${values.startDate}T${values.startTime}:00`
      : `${values.startDate}T00:00:00`;

    let vege: string | null = null;
    if (values.endDate || values.endTime) {
      const endDate = values.endDate || values.startDate;
      const endTime = values.endTime || '00:00';
      vege = `${endDate}T${endTime}:00`;
    }

    // Combine notes with otherCreators and customRadioInput
    let combinedNotes = values.notes || '';
    if (values.otherCreators && values.otherCreators.trim()) {
      const otherCreatorsNote = `\n\n -------- További érintett személyek mező tartalma: --> ${values.otherCreators.trim()} --------`;
      combinedNotes = combinedNotes
        ? `${combinedNotes}${otherCreatorsNote}`
        : otherCreatorsNote.trim();
    }
    if (values.customRadioInput && values.customRadioInput.trim()) {
      const customCategoryNote = `\n\n -------- Egyéb kategória részletesen: --> ${values.customRadioInput.trim()} --------`;
      combinedNotes = combinedNotes
        ? `${combinedNotes}${customCategoryNote}`
        : customCategoryNote.trim();
    }

    const submitBody = {
      input: {
        kezdete,
        vege,
        nev: values.eventName,
        leiras: values.description || null,
        infoUrl: values.infoUrl || null,
        jegyUrl: values.ticketUrl || null,
        kepek: values.uploadedImages?.length ? values.uploadedImages : null,
        szemelyek: values.selectedCreators.length ? values.selectedCreators : null,
        kulturalisTipus: values.selectedType ?? null,
        kulturalisAltipus: values.selectedSubtype ?? null,
        helyszin: values.useCustomLocation ? values.customLocation || null : null,
        intezmeny: values.selectedInstitution ?? null,
        megjegyzes: combinedNotes || null,
        esemenyKategoria: values.eventCategory ?? null,
      },
    };

    try {
      const response = await fetch('/api/submit-event', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          submitBody,
          turnstileToken,
        }),
      });

      const data = await response.json();

      if (response.ok && data.success) {
        if (!completedSteps.includes(3)) {
          setCompletedSteps([...completedSteps, 3]);
        }
        setCurrentStep(4);
        toast({
          variant: 'success',
          title: t('errors.submitSuccess'),
          description: t('errors.submitSuccessMessage'),
        });
      } else {
        console.error('Submit failed:', {
          status: response.status,
          data,
        });
        toast({
          variant: 'destructive',
          title: t('errors.submitError'),
          description: data.message || t('errors.submitErrorMessage'),
        });
      }
    } catch (error) {
      console.error('Submit error:', error);
      toast({
        variant: 'destructive',
        title: t('errors.submitError'),
        description: t('errors.submitErrorMessage'),
      });
    }
  };

  const renderStep = () => {
    switch (currentStep) {
      case 1:
        return <StepCreators control={control} />;
      case 2:
        return (
          <StepDateAndLocation
            control={control}
            watch={watch}
            setValue={setValue}
            institutionList={institutionList}
            errors={errors}
          />
        );
      case 3:
        return (
          <>
            <StepDetailsAndCategory
              categories={categories}
              control={control}
              // watch={watch}
              // setValue={setValue}
            />
            <div className="mt-6">
              <TurnstileWidget onToken={setTurnstileToken} />
            </div>
          </>
        );
      case 4:
        return (
          <StepSuccess
            onReset={() => {
              reset();
              setCurrentStep(1);
              setCompletedSteps([]);
            }}
          />
        );
      default:
        return null;
    }
  };
  // DA6C6C
  // 819A91
  // 748DAE
  // 7e7e7e

  return (
    <section className="event-submit relative w-full overflow-hidden bg-white text-[#151720]">
      <div
        className="pointer-events-none absolute inset-0"
        style={{
          backgroundImage: `
        radial-gradient(circle at center, #b8dadd 10%, transparent 50%)
      `,
          opacity: 0.6,
          mixBlendMode: 'multiply',
        }}
      />

      <div className="relative mx-auto max-w-boxed px-site py-6 sm:py-8">
        {/* Scroll target */}
        <div ref={formTopRef} />

        {/* Header */}
        <div className="border-b border-[#151720]/10 pb-8 lg:pb-12">
          <div className="mx-auto w-full max-w-3xl">
            <h1 className="text-2xl sm:text-3xl lg:text-4xl font-semibold uppercase tracking-[0.14em] text-[#151720]">
              {t('pageTitle')}
            </h1>
            <p className="text-sm sm:text-base text-[#151720]/70 mt-3">
              {t.rich('pageSubtitle', {
                academyLink: (chunks) => (
                  <Link
                    href={{ pathname: '/alkotok' }}
                    className="underline underline-offset-4 decoration-[#151720]/30 hover:decoration-[#151720] transition-colors"
                  >
                    {chunks}
                  </Link>
                ),
                calendarLink: (chunks) => (
                  <Link
                    href={{ pathname: '/programok' }}
                    className="underline underline-offset-4 decoration-[#151720]/30 hover:decoration-[#151720] transition-colors"
                  >
                    {chunks}
                  </Link>
                ),
              })}
            </p>
          </div>
        </div>

        <div className="mt-10">
          {/* Form Content */}
          <div className="min-w-0">
            <form onSubmit={handleSubmit(onSubmit)} className="mx-auto w-full max-w-3xl">
              <div className="border border-[#151720]/10 bg-white/85 px-5 py-6 sm:px-6 sm:py-8 shadow-[0_24px_60px_-50px_rgba(20,25,40,0.2)]">
                {currentStep < 4 && (
                  <div className="border-b border-[#151720]/10 pb-6 mb-6">
                    <div className="flex items-end justify-between gap-4">
                      <h2 className="text-2xl sm:text-3xl font-semibold uppercase tracking-[0.08em] text-[#151720]">
                        {activeStep?.label}
                      </h2>
                      <div className="t-caption tone-soft uppercase">
                        {currentStep} / {STEPS.length}
                      </div>
                    </div>
                    <div
                      className="mt-3 h-1 w-full bg-[#151720]/10"
                      role="progressbar"
                      aria-valuenow={currentStep}
                      aria-valuemin={1}
                      aria-valuemax={STEPS.length}
                      aria-label={`${currentStep} / ${STEPS.length}`}
                    >
                      <div
                        className="h-1 bg-gradient-to-r from-[#151720] to-mma-blue transition-all duration-300"
                        style={{ width: `${progressPercent}%` }}
                      />
                    </div>
                  </div>
                )}

                <div className="event-submit-fields w-full">{renderStep()}</div>
              </div>

              {/* Navigation Buttons */}
              {currentStep < 4 && (
                <div className="mt-6 flex flex-col-reverse gap-3 sm:flex-row sm:items-center sm:justify-between">
                  <Button
                    type="button"
                    variant="outline"
                    onClick={prevStep}
                    disabled={currentStep === 1}
                    className="flex items-center gap-2 border-[#151720]/30 text-[#151720]/70 hover:border-[#151720]/60 hover:text-[#151720] hover:bg-white disabled:opacity-40 uppercase tracking-[0.2em] text-xs sm:text-sm"
                  >
                    <ChevronLeft className="w-4 h-4" />
                    {t('navigation.back')}
                  </Button>

                  {currentStep < 3 ? (
                    <Button
                      type="button"
                      onClick={nextStep}
                      className="flex items-center gap-2 bg-[#151720] text-white hover:bg-[#151720]/85 uppercase tracking-[0.2em] text-xs sm:text-sm"
                    >
                      {t('navigation.next')}
                      <ChevronRight className="w-4 h-4" />
                    </Button>
                  ) : (
                    <Button
                      type="button"
                      onClick={nextStep}
                      disabled={isSubmitting}
                      className="flex items-center gap-2 bg-[#151720] text-white hover:bg-[#151720]/85 uppercase tracking-[0.2em] text-xs sm:text-sm disabled:opacity-40"
                    >
                      {isSubmitting ? t('navigation.submitting') : t('navigation.submit')}
                      <Send className="w-4 h-4" />
                    </Button>
                  )}
                </div>
              )}
            </form>
          </div>
        </div>
      </div>
    </section>
  );
}
