'use client'

import * as React from 'react'
import { ArrowRight, Briefcase, Beaker, Building2, Newspaper, TrendingUp, Microscope, Mail, Phone, MapPin, Check } from 'lucide-react'
import { useRouter } from '@/lib/router'
import { PageShell, PageHero, Section, SectionHeading, Reveal, Eyebrow, Card, DefRow, LabeledDivider, Pill } from '@/components/site/ui'
import { useToast } from '@/hooks/use-toast'
import { toast as sonnerToast } from 'sonner'

const INQUIRY_TYPES = [
  { id: 'business', icon: Briefcase, t: 'Business Development', d: 'Partnerships, licensing, distribution and strategic alliances.', topics: ['Partnership', 'Licensing', 'Distribution', 'Strategic alliance'] },
  { id: 'api', icon: Beaker, t: 'API Sales', d: 'Active pharmaceutical ingredients, excipients and raw materials.', topics: ['API inquiry', 'Excipients', 'Custom synthesis', 'Documentation'] },
  { id: 'cdmo', icon: Building2, t: 'CDMO Services', d: 'Contract development and manufacturing for pharmaceutical and biotech clients.', topics: ['Formulation', 'Analytical', 'Tech transfer', 'Commercial supply'] },
  { id: 'media', icon: Newspaper, t: 'Media', d: 'Press inquiries, interviews and media materials.', topics: ['Press inquiry', 'Interview', 'Embargoed material', 'Site visit'] },
  { id: 'investor', icon: TrendingUp, t: 'Investor Relations', d: 'Investor inquiries, financial reporting and ESG.', topics: ['Investor inquiry', 'Financial reports', 'ESG', 'Analyst access'] },
  { id: 'scientific', icon: Microscope, t: 'Scientific Collaborations', d: 'Research partnerships, academic collaborations and scientific exchange.', topics: ['Research collaboration', 'Academic partnership', 'Pre-clinical', 'Clinical'] },
]

const OFFICES = [
  { city: 'Global Headquarters', region: 'Espandiar Pharmaceuticals — Global Operations', note: 'Corporate functions, R&D leadership and global quality.' },
  { city: 'Research Hub — Europe', region: 'Discovery, translational science, CMC development', note: 'Medicinal chemistry, biologics, analytical development.' },
  { city: 'Research Hub — North America', region: 'Clinical development, regulatory affairs', note: 'Clinical operations, biostatistics, regulatory strategy.' },
  { city: 'Manufacturing — Asia Pacific', region: 'Oral solid, sterile, lyophilized manufacturing', note: 'Commercial manufacturing and CDMO capacity.' },
  { city: 'Manufacturing — Middle East & North Africa', region: 'Regional production and distribution', note: 'Serving MENA and neighboring markets.' },
  { city: 'Biotechnology Center', region: 'Cell line development, bioprocessing', note: 'mAb, recombinant protein and emerging modality development.' },
]

export function ContactPage() {
  const [activeType, setActiveType] = React.useState<string>('business')
  const [submitted, setSubmitted] = React.useState(false)
  const [form, setForm] = React.useState({
    name: '',
    organization: '',
    email: '',
    phone: '',
    subject: '',
    message: '',
    consent: false,
  })

  const [isSubmitting, setIsSubmitting] = React.useState(false)

  const active = INQUIRY_TYPES.find((t) => t.id === activeType)!

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!form.name || !form.email || !form.message) {
      sonnerToast.error('Please complete all required fields.')
      return
    }
    if (!form.consent) {
      sonnerToast.error('Please acknowledge the privacy notice.')
      return
    }
    setIsSubmitting(true)
    try {
      const res = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ...form, inquiryType: activeType }),
      })
      const data = await res.json()
      if (!res.ok) {
        sonnerToast.error(data.error || 'Submission failed. Please try again.')
        return
      }
      sonnerToast.success(data.message || 'Inquiry received. We will respond within two business days.')
      setSubmitted(true)
      setForm({ name: '', organization: '', email: '', phone: '', subject: '', message: '', consent: false })
    } catch {
      sonnerToast.error('Network error. Please check your connection and try again.')
    } finally {
      setIsSubmitting(false)
    }
  }

  const update = (k: keyof typeof form, v: string | boolean) => {
    setForm((prev) => ({ ...prev, [k]: v }))
  }

  return (
    <PageShell>
      <PageHero
        index="01"
        eyebrow="Contact Espandiar"
        title="Let&apos;s start"
        highlight="a conversation."
        lead="Espandiar welcomes inquiries from healthcare professionals, partners, suppliers, investors, journalists, researchers and patients. Please select the inquiry type that best matches your need."
      />

      {/* Inquiry type selector */}
      <Section tone="light">
        <SectionHeading
          index="02"
          eyebrow="Choose your pathway"
          title="Six pathways."
          highlight="One team."
          lead="Each inquiry pathway routes to a dedicated Espandiar team with the appropriate expertise. Select the option that best matches your inquiry to reach the right people quickly."
        />
        <div className="mt-12 grid gap-4 md:grid-cols-2 lg:grid-cols-3">
          {INQUIRY_TYPES.map((t, i) => {
            const Icon = t.icon
            const isActive = activeType === t.id
            return (
              <Reveal key={t.id} delay={(i % 3) * 0.08}>
                <button
                  onClick={() => {
                    setActiveType(t.id)
                    setSubmitted(false)
                  }}
                  className={`group flex h-full w-full flex-col rounded-[26px] border p-7 text-left transition ${
                    isActive
                      ? 'border-[#0d5d50] bg-[#0d5d50]/5 dark:border-[#8fb9ad] dark:bg-[#8fb9ad]/5'
                      : 'border-border bg-card hover:border-[#0d5d50]/40 dark:hover:border-[#8fb9ad]/40'
                  }`}
                >
                  <div className="flex items-center justify-between">
                    <div
                      className={`grid h-12 w-12 place-items-center rounded-2xl ${
                        isActive
                          ? 'bg-[#0d5d50] text-white dark:bg-[#8fb9ad] dark:text-[#0c1311]'
                          : 'bg-[#0d5d50]/10 text-[#0d5d50] dark:bg-[#8fb9ad]/10 dark:text-[#8fb9ad]'
                      }`}
                    >
                      <Icon className="h-5 w-5" />
                    </div>
                    {isActive && (
                      <Check className="h-5 w-5 text-[#0d5d50] dark:text-[#8fb9ad]" />
                    )}
                  </div>
                  <h3 className="mt-5 text-lg font-semibold tracking-[-0.02em]">{t.t}</h3>
                  <p className="mt-3 flex-1 text-sm leading-6 text-muted-foreground">{t.d}</p>
                  <div className="mt-5 flex flex-wrap gap-1.5">
                    {t.topics.slice(0, 3).map((topic) => (
                      <span
                        key={topic}
                        className="rounded-full bg-muted px-2.5 py-1 text-[10px] font-bold uppercase tracking-[0.1em] text-muted-foreground"
                      >
                        {topic}
                      </span>
                    ))}
                  </div>
                </button>
              </Reveal>
            )
          })}
        </div>
      </Section>

      {/* Contact form */}
      <Section tone="pearl">
        <SectionHeading
          index="03"
          eyebrow={active.t}
          title="Send us"
          highlight="a message."
          lead={active.d}
        />
        <div className="mt-12 grid gap-8 lg:grid-cols-[1.4fr_0.6fr]">
          <Reveal>
            {submitted ? (
              <Card className="bg-card">
                <div className="flex flex-col items-center py-12 text-center">
                  <div className="grid h-16 w-16 place-items-center rounded-full bg-[#0d5d50]/10 text-[#0d5d50] dark:bg-[#8fb9ad]/10 dark:text-[#8fb9ad]">
                    <Check className="h-8 w-8" />
                  </div>
                  <h3 className="mt-6 text-2xl font-semibold tracking-[-0.03em]">Inquiry received.</h3>
                  <p className="mt-3 max-w-md text-sm leading-6 text-muted-foreground">
                    Thank you for contacting Espandiar. Our {active.t} team will
                    respond within two business days. For urgent regulatory or
                    pharmacovigilance matters, please use the dedicated channels
                    listed on this page.
                  </p>
                  <button
                    onClick={() => setSubmitted(false)}
                    className="mt-8 rounded-full bg-[#0d5d50] px-6 py-3.5 text-sm font-bold text-white dark:bg-[#8fb9ad] dark:text-[#0c1311]"
                  >
                    Send another inquiry
                  </button>
                </div>
              </Card>
            ) : (
              <Card className="bg-card">
                <form onSubmit={handleSubmit} className="space-y-5">
                  <div className="grid gap-5 sm:grid-cols-2">
                    <Field
                      label="Full name *"
                      value={form.name}
                      onChange={(v) => update('name', v)}
                      placeholder="Dr. Jane Doe"
                      required
                    />
                    <Field
                      label="Organization"
                      value={form.organization}
                      onChange={(v) => update('organization', v)}
                      placeholder="Company / Institution"
                    />
                  </div>
                  <div className="grid gap-5 sm:grid-cols-2">
                    <Field
                      label="Email *"
                      type="email"
                      value={form.email}
                      onChange={(v) => update('email', v)}
                      placeholder="jane.doe@example.com"
                      required
                    />
                    <Field
                      label="Phone"
                      type="tel"
                      value={form.phone}
                      onChange={(v) => update('phone', v)}
                      placeholder="+1 (555) 000-0000"
                    />
                  </div>
                  <Field
                    label="Subject"
                    value={form.subject}
                    onChange={(v) => update('subject', v)}
                    placeholder="Brief subject of your inquiry"
                  />
                  <div>
                    <label className="mb-2 block text-xs font-bold uppercase tracking-[0.14em] text-muted-foreground">
                      Message *
                    </label>
                    <textarea
                      value={form.message}
                      onChange={(e) => update('message', e.target.value)}
                      required
                      rows={6}
                      placeholder="Please provide the details of your inquiry. Do not include confidential information at this stage."
                      className="w-full rounded-xl border border-border bg-background px-4 py-3 text-sm outline-none transition focus:border-[#0d5d50] dark:focus:border-[#8fb9ad]"
                    />
                  </div>
                  <label className="flex items-start gap-3 text-sm leading-6 text-muted-foreground">
                    <input
                      type="checkbox"
                      checked={form.consent}
                      onChange={(e) => update('consent', e.target.checked)}
                      className="mt-1 h-4 w-4 rounded border-border accent-[#0d5d50] dark:accent-[#8fb9ad]"
                    />
                    <span>
                      I acknowledge that the information provided will be
                      processed in accordance with Espandiar&apos;s privacy
                      notice and applicable data protection laws (including
                      GDPR). I understand that Espandiar may contact me in
                      response to this inquiry. *
                    </span>
                  </label>
                  <button
                    type="submit"
                    disabled={isSubmitting}
                    className="inline-flex items-center gap-2 rounded-full bg-[#0d5d50] px-7 py-4 text-sm font-bold text-white transition hover:bg-[#0b3b34] disabled:opacity-60 disabled:cursor-not-allowed dark:bg-[#8fb9ad] dark:text-[#0c1311] dark:hover:bg-[#a8c8be]"
                  >
                    {isSubmitting ? 'Sending…' : 'Send inquiry'}
                    {!isSubmitting && <ArrowRight className="h-4 w-4" />}
                  </button>
                </form>
              </Card>
            )}
          </Reveal>

          <Reveal delay={0.1}>
            <Card className="bg-card">
              <Eyebrow>Direct channels</Eyebrow>
              <div className="mt-6 space-y-5 text-sm">
                <div className="flex items-start gap-3">
                  <Mail className="mt-0.5 h-4 w-4 text-[#0d5d50] dark:text-[#8fb9ad]" />
                  <div>
                    <b className="block text-xs font-bold uppercase tracking-[0.12em] text-muted-foreground">Email</b>
                    <p className="mt-1">Info@espandiarpharma.com</p>
                  </div>
                </div>
                <div className="flex items-start gap-3">
                  <Phone className="mt-0.5 h-4 w-4 text-[#0d5d50] dark:text-[#8fb9ad]" />
                  <div>
                    <b className="block text-xs font-bold uppercase tracking-[0.12em] text-muted-foreground">Phone (Global HQ)</b>
                    <p className="mt-1">+49 1522 3449208</p>
                  </div>
                </div>
                <div className="flex items-start gap-3">
                  <Microscope className="mt-0.5 h-4 w-4 text-[#0d5d50] dark:text-[#8fb9ad]" />
                  <div>
                    <b className="block text-xs font-bold uppercase tracking-[0.12em] text-muted-foreground">Pharmacovigilance</b>
                    <p className="mt-1">safety@espandiarPharma.com</p>
                    <p className="mt-1 text-xs text-muted-foreground">24/7 adverse event reporting</p>
                  </div>
                </div>
                <div className="flex items-start gap-3">
                  <Briefcase className="mt-0.5 h-4 w-4 text-[#0d5d50] dark:text-[#8fb9ad]" />
                  <div>
                    <b className="block text-xs font-bold uppercase tracking-[0.12em] text-muted-foreground">Ethics hotline</b>
                    <p className="mt-1">ethics@espandiarPharma.com</p>
                    <p className="mt-1 text-xs text-muted-foreground">Confidential, 24/7, third-party operated</p>
                  </div>
                </div>
              </div>
              <LabeledDivider label="Response time" className="mt-6" />
              <p className="mt-4 text-xs leading-5 text-muted-foreground">
                We respond to most inquiries within two business days.
                Pharmacovigilance reports are reviewed by qualified safety
                personnel within 24 hours. Ethics hotline reports are
                reviewed by the Chief Compliance Officer.
              </p>
            </Card>
          </Reveal>
        </div>
      </Section>

      {/* Offices */}
      <Section tone="light">
        <SectionHeading
          index="04"
          eyebrow="Global offices"
          title="Find an office"
          highlight="near you."
          lead="Espandiar operates across 52 countries, with research hubs, manufacturing sites and commercial offices around the world."
        />
        <div className="mt-12 grid gap-4 md:grid-cols-2 lg:grid-cols-3">
          {OFFICES.map((o, i) => (
            <Reveal key={o.city} delay={(i % 3) * 0.08}>
              <Card className="h-full">
                <div className="flex items-center gap-3">
                  <div className="grid h-10 w-10 place-items-center rounded-xl bg-[#0d5d50]/10 text-[#0d5d50] dark:bg-[#8fb9ad]/10 dark:text-[#8fb9ad]">
                    <MapPin className="h-4 w-4" />
                  </div>
                  <Pill tone="emerald">{`0${i + 1}`}</Pill>
                </div>
                <h3 className="mt-5 text-base font-semibold tracking-[-0.02em]">{o.city}</h3>
                <p className="mt-2 text-sm leading-6 text-muted-foreground">{o.region}</p>
                <p className="mt-3 text-xs leading-5 text-muted-foreground/80">{o.note}</p>
              </Card>
            </Reveal>
          ))}
        </div>
      </Section>

      {/* Important notices */}
      <Section tone="dark">
        <div className="grid gap-8 lg:grid-cols-2">
          <Reveal>
            <Card tone="dark">
              <Eyebrow tone="sage">Pharmacovigilance</Eyebrow>
              <h3 className="mt-4 text-xl font-semibold tracking-[-0.02em]">Reporting adverse events</h3>
              <p className="mt-4 text-sm leading-6 text-white/65">
                Healthcare professionals and patients should report adverse
                events, product quality complaints or medication errors to
                Espandiar&apos;s pharmacovigilance department. Reports can be
                submitted by email, phone or through the relevant national
                reporting system. Espandiar reviews all reports in
                accordance with ICH E2D and applicable regulations.
              </p>
              <p className="mt-3 text-sm font-semibold text-white">safety@espandiarPharma.com</p>
            </Card>
          </Reveal>
          <Reveal delay={0.1}>
            <Card tone="dark">
              <Eyebrow tone="sage">Medical information</Eyebrow>
              <h3 className="mt-4 text-xl font-semibold tracking-[-0.02em]">Healthcare professional inquiries</h3>
              <p className="mt-4 text-sm leading-6 text-white/65">
                Healthcare professionals seeking product-specific medical
                information — including prescribing information, summary of
                product characteristics, clinical data and drug
                interactions — are directed to our medical information
                service. Espandiar&apos;s medical information team provides
                scientifically accurate, balanced and timely responses.
              </p>
              <p className="mt-3 text-sm font-semibold text-white">medicalinfo@espandiarPharma.com</p>
            </Card>
          </Reveal>
        </div>
        <Reveal className="mt-10">
          <LabeledDivider label="Privacy & data protection" tone="dark" />
          <p className="mt-4 max-w-3xl text-xs leading-5 text-white/55">
            Espandiar processes personal data in accordance with its privacy
            notice and applicable laws including the EU General Data
            Protection Regulation (GDPR), the California Consumer Privacy
            Act (CCPA) and other applicable data protection regulations.
            Personal data submitted through this form is used solely for the
            purpose of responding to your inquiry and is retained in
            accordance with Espandiar&apos;s data retention policy.
          </p>
        </Reveal>
      </Section>
    </PageShell>
  )
}

function Field({
  label,
  value,
  onChange,
  placeholder,
  type = 'text',
  required,
}: {
  label: string
  value: string
  onChange: (v: string) => void
  placeholder?: string
  type?: string
  required?: boolean
}) {
  return (
    <div>
      <label className="mb-2 block text-xs font-bold uppercase tracking-[0.14em] text-muted-foreground">
        {label}
      </label>
      <input
        type={type}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        placeholder={placeholder}
        required={required}
        className="w-full rounded-xl border border-border bg-background px-4 py-3 text-sm outline-none transition focus:border-[#0d5d50] dark:focus:border-[#8fb9ad]"
      />
    </div>
  )
}
