import { useState } from 'react'
import { useForm } from 'react-hook-form'
import { z } from 'zod'
import { zodResolver } from '@hookform/resolvers/zod'
import Seo from '../components/Seo'
import Reveal from '../components/Reveal'
import PageHero from '../components/PageHero'
import { MapPin, Phone, Mail, WhatsApp } from '../components/icons'
import { useContent, getSettings, submitContact } from '../lib/api'

const schema = z.object({
  name: z.string().min(2, 'Please enter your name'),
  email: z.string().email('Please enter a valid email'),
  phone: z.string().optional(),
  message: z.string().min(10, 'Tell us a little more (10+ characters)'),
})
type FormData = z.infer<typeof schema>

export default function Contact() {
  const settings = useContent(getSettings)
  const [status, setStatus] = useState<'idle' | 'sent' | 'error'>('idle')
  const {
    register,
    handleSubmit,
    reset,
    formState: { errors, isSubmitting },
  } = useForm<FormData>({ resolver: zodResolver(schema) })

  if (!settings) return <div className="min-h-screen" />
  const phoneHref = `tel:${settings.phone.replace(/[^+\d]/g, '')}`

  const onSubmit = async (data: FormData) => {
    const ok = await submitContact(data)
    setStatus(ok ? 'sent' : 'error')
    if (ok) reset()
  }

  const inputCls =
    'w-full rounded-xl border border-ocean-500/15 bg-white px-4 py-3 text-[0.95rem] outline-none transition-colors focus:border-turquoise-500'

  return (
    <>
      <Seo
        title={`Contact — ${settings.company_name}`}
        description={`Book your treatment: ${settings.phone}, WhatsApp ${settings.whatsapp}, or ${settings.email}. ${settings.address}.`}
      />
      <PageHero
        kicker="Get in Touch"
        title="Begin Your Journey to Calm"
        lead="Call, WhatsApp, email, or send the form — we'll take care of the rest."
      />

      <section className="py-20">
        <div className="wrap grid items-start gap-12 lg:grid-cols-[1fr_1.1fr]">
          <Reveal>
            <div className="grid gap-4">
              {[
                { Icon: MapPin, title: 'Visit Us', line: settings.address },
                { Icon: Phone, title: 'Call Us', line: settings.phone, href: phoneHref },
                { Icon: WhatsApp, title: 'WhatsApp', line: settings.whatsapp, href: settings.social.whatsapp },
                { Icon: Mail, title: 'Email', line: settings.email, href: `mailto:${settings.email}` },
              ].map(({ Icon, title, line, href }) => (
                <div key={title} className="glass-card flex items-start gap-4 px-6 py-5 shadow-card">
                  <div className="grid h-11 w-11 shrink-0 place-items-center rounded-xl bg-gradient-to-br from-turquoise-500 to-turquoise-400 text-white">
                    <Icon />
                  </div>
                  <div>
                    <strong className="block text-[0.92rem]">{title}</strong>
                    {href ? (
                      <a href={href} className="text-[0.9rem] text-muted transition-colors hover:text-turquoise-500">
                        {line}
                      </a>
                    ) : (
                      <span className="text-[0.9rem] text-muted">{line}</span>
                    )}
                  </div>
                </div>
              ))}
              <div className="rounded-3xl bg-gradient-to-br from-ocean-700 to-turquoise-500 p-8 text-white shadow-soft">
                <h3 className="mb-4 text-[1.3rem]">Business Hours</h3>
                <table className="w-full text-[0.9rem]">
                  <tbody>
                    {settings.hours.map((h) => (
                      <tr key={h.day} className="border-b border-white/[0.18] last:border-0">
                        <td className="py-2">{h.day}</td>
                        <td className={`py-2 text-right font-semibold ${h.closed ? 'text-[#ffc4bc]' : 'text-turquoise-200'}`}>
                          {h.time}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </Reveal>

          <Reveal delay={0.12}>
            <form
              onSubmit={handleSubmit(onSubmit)}
              className="rounded-[28px] bg-white p-8 shadow-soft lg:p-10"
              noValidate
            >
              <h2 className="sec-title !text-[1.7rem]">Send Us a Message</h2>
              <p className="mb-7 text-muted">We usually reply within a few hours.</p>

              <div className="grid gap-5">
                <div>
                  <label htmlFor="name" className="mb-1.5 block text-[0.88rem] font-semibold">
                    Name *
                  </label>
                  <input id="name" className={inputCls} placeholder="Your full name" {...register('name')} />
                  {errors.name && <p className="mt-1 text-[0.82rem] text-coral-500">{errors.name.message}</p>}
                </div>
                <div className="grid gap-5 sm:grid-cols-2">
                  <div>
                    <label htmlFor="email" className="mb-1.5 block text-[0.88rem] font-semibold">
                      Email *
                    </label>
                    <input id="email" type="email" className={inputCls} placeholder="you@example.com" {...register('email')} />
                    {errors.email && <p className="mt-1 text-[0.82rem] text-coral-500">{errors.email.message}</p>}
                  </div>
                  <div>
                    <label htmlFor="phone" className="mb-1.5 block text-[0.88rem] font-semibold">
                      Phone / WhatsApp
                    </label>
                    <input id="phone" className={inputCls} placeholder="Optional" {...register('phone')} />
                  </div>
                </div>
                <div>
                  <label htmlFor="message" className="mb-1.5 block text-[0.88rem] font-semibold">
                    Message *
                  </label>
                  <textarea
                    id="message"
                    rows={5}
                    className={inputCls}
                    placeholder="Which treatment are you interested in? Preferred dates?"
                    {...register('message')}
                  />
                  {errors.message && <p className="mt-1 text-[0.82rem] text-coral-500">{errors.message.message}</p>}
                </div>
                <button type="submit" disabled={isSubmitting} className="btn-primary justify-center disabled:opacity-60">
                  {isSubmitting ? 'Sending…' : 'Send Message'}
                </button>
                {status === 'sent' && (
                  <p className="rounded-xl bg-turquoise-50 px-4 py-3 text-[0.9rem] font-medium text-ocean-700">
                    Thank you! Your message has been sent — we'll be in touch shortly.
                  </p>
                )}
                {status === 'error' && (
                  <p className="rounded-xl bg-coral-400/10 px-4 py-3 text-[0.9rem] font-medium text-coral-500">
                    Something went wrong sending your message. Please try WhatsApp or email instead.
                  </p>
                )}
              </div>
            </form>
          </Reveal>
        </div>
      </section>

      <Reveal>
        <iframe
          title={`${settings.company_name} location map`}
          src={`https://www.google.com/maps?q=${encodeURIComponent(settings.map_query)}&output=embed`}
          loading="lazy"
          referrerPolicy="no-referrer-when-downgrade"
          className="h-[420px] w-full border-0 saturate-[0.9]"
        />
      </Reveal>
    </>
  )
}
