
import React, { useEffect, useState } from 'react';
import type { ReactElement } from 'react';
import { ToastContainer, toast } from 'react-toastify';
import Head from 'next/head';
import BaseButton from '../components/BaseButton';
import CardBox from '../components/CardBox';
import BaseIcon from "../components/BaseIcon";
import { mdiShieldCheck } from '@mdi/js';
import LayoutGuest from '../layouts/Guest';
import { Field, Form, Formik } from 'formik';
import FormField from '../components/FormField';
import { useRouter } from 'next/router';
import { getPageTitle } from '../config';
import Link from 'next/link';
import axios from "axios";
import { getPexelsImage, getPexelsVideo } from '../helpers/pexels'

export default function Forgot() {
  const [loading, setLoading] = React.useState(false)
  const router = useRouter();
  const notify = (type, msg) => toast(msg, { type });

  const [illustrationImage, setIllustrationImage] = useState({
      src: undefined,
      photographer: undefined,
      photographer_url: undefined,
  })
  const [illustrationVideo, setIllustrationVideo] = useState({ video_files: [] })
  const [contentType, setContentType] = useState('image');

  useEffect(() => {
      async function fetchData() {
          const image = await getPexelsImage()
          const video = await getPexelsVideo()
          setIllustrationImage(image);
          setIllustrationVideo(video);
      }
      fetchData();
  }, []);

  const handleSubmit = async (value) => {
    setLoading(true)
    try {
      await axios.post('/auth/send-password-reset-email', value);
      setLoading(false)
      notify('success', 'Please check your email for reset link');
      setTimeout(async () => {
        await router.push('/login')
      }, 3000)
    } catch (error) {
      setLoading(false)
      console.log('error: ', error)
      notify('error', 'Something went wrong. Try again')
    }
  };

  const imageBlock = (image) => (
      <div className="hidden lg:flex flex-col justify-end relative flex-grow-0 flex-shrink-0 w-1/2 overflow-hidden"
          style={{
              backgroundImage: `${image ? `url(${image.src?.original})` : 'linear-gradient(rgba(16, 185, 129, 0.1), rgba(6, 78, 59, 0.2))'}`,
              backgroundSize: 'cover',
              backgroundPosition: 'center',
              backgroundRepeat: 'no-repeat',
          }}>
          <div className="absolute inset-0 bg-emerald-900/20 backdrop-brightness-75"></div>
          <div className="relative z-10 p-12 text-white">
              <h1 className="text-4xl font-black mb-4">Secure Your Account.</h1>
              <p className="text-lg text-emerald-50/80 max-w-md leading-relaxed">
                  We&apos;ll help you get back into your account safely and securely.
              </p>
          </div>
          <div className="flex justify-center w-full bg-black/40 py-2 relative z-10">
              <a className="text-[10px] text-white/60 hover:text-white transition-colors" href={image?.photographer_url} target="_blank" rel="noreferrer">
                  Photo by {image?.photographer} on Pexels
              </a>
          </div>
      </div>
  )

  return (
    <div className="min-h-screen bg-slate-50 font-sans">
      <Head>
        <title>{getPageTitle('Forgot Password')}</title>
      </Head>

      <div className="flex flex-row min-h-screen">
          {imageBlock(illustrationImage)}
          
          <div className="w-full lg:w-1/2 flex items-center justify-center p-8 lg:p-16">
              <div className="w-full max-w-md space-y-8">
                  {/* Branding */}
                  <div className="flex flex-col items-center mb-8">
                      <Link href="/" className="flex items-center gap-3 group mb-6">
                          <div className="w-12 h-12 bg-emerald-500 rounded-2xl flex items-center justify-center shadow-xl shadow-emerald-500/20 group-hover:scale-110 transition-transform">
                              <BaseIcon path={mdiShieldCheck} size={28} className="text-white" />
                          </div>
                          <span className="text-2xl font-black tracking-tight text-slate-900">
                              Fix-It-Local<span className="text-emerald-500 italic">™</span>
                          </span>
                      </Link>
                      <h2 className="text-3xl font-bold text-slate-900 text-center">Forgot Password?</h2>
                      <p className="text-slate-500 mt-2 text-center">Enter your email and we&apos;ll send you a link to reset your password.</p>
                  </div>

                  <CardBox className="shadow-2xl border-none rounded-[2rem] p-4 lg:p-6">
                    <Formik
                      initialValues={{
                        email: '',
                      }}
                      onSubmit={(values) => handleSubmit(values)}
                    >
                      <Form className="space-y-6">
                        <FormField 
                            label='Email Address'
                            labelColor="text-slate-700 font-bold"
                        >
                          <Field name='email' type='email' placeholder="name@company.com" className="rounded-xl border-slate-200 focus:border-emerald-500 focus:ring-emerald-500" />
                        </FormField>

                        <div className="pt-2">
                            <BaseButton
                                className={'w-full py-4 rounded-xl font-bold text-lg shadow-lg shadow-emerald-500/20'}
                                type='submit'
                                label={loading ? 'Sending link...' : 'Send Reset Link'}
                                color='success'
                                disabled={loading}
                            />
                        </div>
                        
                        <div className="text-center pt-2">
                            <Link className="font-bold text-emerald-600 hover:text-emerald-700 text-sm" href={'/login'}>
                                Back to Login
                            </Link>
                        </div>
                       </Form>
                    </Formik>
                  </CardBox>

                  <div className="text-center text-slate-400 text-xs pt-8">
                      © 2026 Fix-It-Local™. All rights reserved. <br/>
                      <Link href='/privacy-policy/' className="hover:text-slate-600 mt-2 inline-block">Privacy Policy</Link>
                  </div>
              </div>
          </div>
      </div>
      <ToastContainer />
    </div>
  );
}

Forgot.getLayout = function getLayout(page: ReactElement) {
  return <LayoutGuest>{page}</LayoutGuest>;
};
