'use client'
import { ButtonArrow, ButtonArrowRight } from '@/components/icons/button-icon'
import { CloseIcon } from '@/components/icons/form-icon'
import { LogoIcon, LogoLgIcon, MasterCardIcon, VisaIcon } from '@/components/icons/layout-icon'
import {
  FaceBookIcon,
  InstagramIcon,
  TelegramIcon,
  TikTokkIcon,
  WhatsAppIcon,
  YoutubeIcon,
} from '@/components/icons/socials'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Section } from '@/components/ui/section'
import Link from 'next/link'
import React, { useState } from 'react'
import { Controller, useForm } from 'react-hook-form'
import { Footer as TFooter } from '@/payload-types'
interface Props {}

const APIURL = '/api/send-email'

import { z } from 'zod'
import { zodResolver } from '@hookform/resolvers/zod'
import { CustomInput } from '@/components/ui/CustomInput'
import { useI18n } from '@/locales/client'

// const schema = z.object({
//   email: z
//     .string()
//     .min(1, 'Email is required')
//     .email('Invalid email format')
//     .max(100, 'Email must be at most 100 characters'),
// })

export const Footer: React.FC<TFooter> = ({
  telegram,
  facebook,
  instagram,
  tiktok,
  whatsapp,
  youtube,
}) => {
  const t = useI18n()

  const schema = z.object({
    email: z
      .string()
      .min(1, t('contactForm.errors.email.min'))
      .email(t('contactForm.errors.email.regex'))
      .max(100, t('contactForm.errors.email.max')),
  })
  const form = useForm<z.infer<typeof schema>>({
    resolver: zodResolver(schema),
    mode: 'onChange',
    defaultValues: {
      email: '',
    },
  })

  const {
    control,
    handleSubmit,
    reset,
    formState: { errors, isSubmitting },
  } = form

  const onSubmit = async (data: z.infer<typeof schema>) => {
    try {
      const res = await fetch(APIURL, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: data.email }),
      })

      if (!res.ok) {
        throw new Error('Failed to submit form')
      }

      reset()
    } catch (e) {
      console.error('Submission error:', e)
    }
  }

  return (
    <>
      <Section sectionClass="relative">
        <div
          style={{
            background:
              'linear-gradient(270deg, #050505 0%, #534F43 63.96%, #534F43 67.56%, #050505 100%)',
          }}
          className="absolute h-[1px] top-0 left-0 w-full bg-base-black"
        ></div>
        <div className="w-full pt-4 tablet:pt-10 xl:pt-6 flex flex-col">
          <div className="flex tablet:items-center tablet:flex-row flex-col gap-y-8 tablet:justify-between">
            <Link className="w-fit" href={'/'}>
              <LogoLgIcon className="max-tablet:hidden" width={269} height={78} />
              <LogoIcon className="tablet:hidden" width={150} height={44} />
            </Link>
            <div className="flex gap-2">
              <VisaIcon />
              <MasterCardIcon />
            </div>
          </div>
          <div className="xl:hidden mt-[56px] max-tablet:grid grid-cols-2 tablet:flex gap-x-6">
            <Button className="text-[#999999] w-fit" variant="link-primary" sizes="btn-link-md">
              <Link href="/catalog">{t('navigation.catalog')}</Link>
            </Button>
            <Button className="text-[#999999] w-fit" variant="link-primary" sizes="btn-link-md">
              <Link href="/rental-terms">{t('navigation.rentalTerms')}</Link>
            </Button>
            <Button className="text-[#999999] w-fit" variant="link-primary" sizes="btn-link-md">
              <Link href="/about-us">{t('navigation.aboutUs')}</Link>
            </Button>
            <Button className="text-[#999999] w-fit" variant="link-primary" sizes="btn-link-md">
              <Link href="/blog">{t('navigation.blog')}</Link>
            </Button>
            <Button className="text-[#999999] w-fit" variant="link-primary" sizes="btn-link-md">
              <Link href="/reviews">{t('navigation.reviews')}</Link>
            </Button>
            <Button className="text-[#999999] w-fit" variant="link-primary" sizes="btn-link-md">
              <Link href="/contacts">{t('navigation.contacts')}</Link>
            </Button>
          </div>
          <div className="mt-10 xl:mt-12 flex  xl:flex-row flex-col xl:items-center xl:justify-between">
            <div className="mt-10 tablet:gap-y-1 xl:mt-0 grid max-xl:order-2 text-base-white  grid-cols-1 tablet:grid-cols-[minmax(0,72px)_1fr] gap-x-2">
              <div className="label-medium-regular h-[18px] tablet:h-8 text-grey-200">
                {t('footer.telephone')}
              </div>
              <div className="label-medium-medium h-8 text-grey-400">+34 641 491 952</div>
              <div className="label-medium-regular h-[18px] tablet:h-8 text-grey-200">{t('footer.email')}</div>
              <div className="label-medium-medium h-8 text-grey-400">
                teslacapitalgroup@gmail.com
              </div>
              <div className="label-medium-regular h-[18px] tablet:h-8 text-grey-200">{t('footer.address')}</div>
              <div className="label-medium-medium h-[32px] tablet:h-8 text-grey-400">
                Calle La Sal, 12, Torrevieja, Alicante, Spain
              </div>
            </div>

            <form
              onSubmit={handleSubmit(onSubmit)}
              className="max-xl:order-1 xl:max-w-[484px] w-full flex flex-col"
            >
              <div className="flex gap-2">
                <div className="flex-1">
                  <Controller
                    name="email"
                    control={control}
                    render={({ field, fieldState }) => (
                      <CustomInput
                        {...field}
                        className="w-full flex-1"
                        label=""
                        placeholder={t('contactForm.placeholders.email')}
                        hasError={!!fieldState.error}
                        errorMessage={fieldState.error?.message}
                        onChange={(e) => {
                          const raw = e.target.value
                          const cleaned = raw.replace(/[^a-zA-Z0-9@._\-]/g, '')
                          field.onChange(cleaned)
                        }}
                        onKeyDown={(e) => {
                          const forbiddenChars = /[^a-zA-Z0-9@._\-]/
                          if (forbiddenChars.test(e.key)) {
                            e.preventDefault()
                          }
                        }}
                      />
                    )}
                  />
                </div>

                <Button
                  type="submit"
                  variant="primary"
                  sizes="btn-lg"
                  className="ml-auto max-tablet:hidden w-fit"
                >
                  <span className="min-w-[76px]">{isSubmitting ? t('footer.submitting') : t('footer.submitButton')}</span>
                </Button>

                <Button
                  sizes="icon-btn-lg"
                  className="w-fit tablet:hidden"
                  iconOnly
                  icon={<ButtonArrowRight className=" " width={24} height={24} fill={'#474746'} />}
                  variant="icon-only-white"
                />
              </div>

              <div className="mt-4">
                <p className="label-medium-regular text-grey-300">
                  {t('footer.newsletter')}
                </p>
              </div>
            </form>
          </div>
          <div className="mt-10 xl:mt-[52px] flex justify-between">
            <div className="flex gap-2">
              {tiktok && (
                <Link href={tiktok} target="_blank" rel="noopener noreferrer">
                  <Button
                    className="w-fit"
                    iconOnly
                    icon={<TikTokkIcon className="w-fit" width={20} height={20} fill={'#F6ECE5'} />}
                    variant="icon-only"
                  />
                </Link>
              )}
              {instagram && (
                <Link href={instagram} target="_blank" rel="noopener noreferrer">
                  <Button
                    className="w-fit"
                    iconOnly
                    icon={
                      <InstagramIcon className="w-fit" width={20} height={20} fill={'#F6ECE5'} />
                    }
                    variant="icon-only"
                  />
                </Link>
              )}
              {facebook && (
                <Link href={facebook} target="_blank" rel="noopener noreferrer">
                  <Button
                    className="w-fit"
                    iconOnly
                    icon={
                      <FaceBookIcon className="w-fit" width={20} height={20} fill={'#F6ECE5'} />
                    }
                    variant="icon-only"
                  />
                </Link>
              )}
              {telegram && (
                <Link href={telegram} target="_blank" rel="noopener noreferrer">
                  <Button
                    className="w-fit"
                    iconOnly
                    icon={
                      <TelegramIcon className="w-fit" width={20} height={20} fill={'#F6ECE5'} />
                    }
                    variant="icon-only"
                  />
                </Link>
              )}
              {whatsapp && (
                <Link href={whatsapp} target="_blank" rel="noopener noreferrer">
                  <Button
                    className="w-fit"
                    iconOnly
                    icon={
                      <WhatsAppIcon className="w-fit" width={20} height={20} fill={'#F6ECE5'} />
                    }
                    variant="icon-only"
                  />
                </Link>
              )}
              {youtube && (
                <Link href={youtube} target="_blank" rel="noopener noreferrer">
                  <Button
                    className="w-fit"
                    iconOnly
                    icon={<YoutubeIcon className="w-fit" width={20} height={20} fill={'#F6ECE5'} />}
                    variant="icon-only"
                  />
                </Link>
              )}
            </div>
            <div className="max-xl:hidden flex gap-x-6">
              <Button className="text-[#999999]" variant="link-primary" sizes="btn-link-md">
                <Link href="/catalog">{t('navigation.catalog')}</Link>
              </Button>
              <Button className="text-[#999999]" variant="link-primary" sizes="btn-link-md">
                <Link href="/rental-terms">{t('navigation.rentalTerms')}</Link>
              </Button>
              <Button className="text-[#999999]" variant="link-primary" sizes="btn-link-md">
                <Link href="/about-us">{t('navigation.aboutUs')}</Link>
              </Button>
              <Button className="text-[#999999]" variant="link-primary" sizes="btn-link-md">
                <Link href="/blog">{t('navigation.blog')}</Link>
              </Button>
              <Button className="text-[#999999]" variant="link-primary" sizes="btn-link-md">
                <Link href="/reviews">{t('navigation.reviews')}</Link>
              </Button>
              <Button className="text-[#999999]" variant="link-primary" sizes="btn-link-md">
                <Link href="/contacts">{t('navigation.contacts')}</Link>
              </Button>
            </div>
          </div>
          <div className="flex max-tablet:gap-x-2 max-xl:flex-wrap gap-y-2 pb-10 xl:pb-8 text-grey-400 label-medium-medium mt-[55px] items-center justify-between">
            <div className="h-8 flex items-center justify-center">
              ©Copyright Inc. 2025 All Rights Reserved
            </div>
            <div className="flex max-xl:hidden items-center gap-x-8">
              <Button className="text-grey-400" variant="link-primary" sizes="btn-link-md">
                <Link href="/privacy-policy">{t('navigation.privacyPolicy')}</Link>
              </Button>
              <Button className="text-grey-400" variant="link-primary" sizes="btn-link-md">
                <Link href="/terms-and-conditions">{t('navigation.termsAndConditions')}</Link>
              </Button>
            </div>
            <Button className="text-grey-400 xl:hidden" variant="link-primary" sizes="btn-link-md">
              <Link href="/privacy-policy">{t('navigation.privacyPolicy')}</Link>
            </Button>
            <Button className="text-grey-400 xl:hidden" variant="link-primary" sizes="btn-link-md">
              <Link href="/terms-and-conditions">{t('navigation.termsAndConditions')}</Link>
            </Button>
            <Button className="text-grey-400" variant="link-primary" sizes="btn-link-md">
              <Link href="https://redrocket.software/" target="_blank">Powered by Red Rocket Software</Link>
            </Button>
          </div>
        </div>
      </Section>
    </>
  )
}
