import AltivateLayout from '@/Layouts/AltivateLayout';
import { useMemo, useState } from "react";
import { ArrowUpRight, Check, ChevronLeft, ChevronRight, Mail, CalendarClock } from "lucide-react";
import { useForm, usePage } from '@inertiajs/react';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/Components/ui/select';

const stats = [
  { k: "25", v: "page written report delivered within 2 weeks" },
  { k: "100%", v: "fee credited toward retainer if you sign within 30 days" },
  { k: "0", v: "obligation to continue — results first, decision after" },
];

const areas = [
  { n: "1", t: "Brand assessment", b: "How clearly you communicate your value. Consistency across touchpoints. Perception vs reality." },
  { n: "2", t: "Digital presence review", b: "Website performance, SEO baseline, conversion rate, lead capture effectiveness." },
  { n: "3", t: "Marketing spend analysis", b: "What you're spending, where, and what evidence exists that it's working." },
  { n: "4", t: "Social media audit", b: "Content quality, audience alignment, conversion path, engagement vs revenue correlation." },
  { n: "5", t: "Competitive landscape", b: "How you compare to direct and indirect competitors. Where you have a genuine edge." },
  { n: "6", t: "Revenue gap identification", b: "The specific gaps between your current state and your growth goal — prioritised by impact." },
];

const locations = ["Nigeria", "UK", "US", "Other"];
const revenues = ["₦5M–50M", "₦50M–200M", "₦200M+", "£30k–150k", "£150k+"];

function dateKey(d: Date) {
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
}

function isWeekday(d: Date) {
  const day = d.getDay();
  return day !== 0 && day !== 6;
}

function formatLongDate(d: Date) {
  return d.toLocaleDateString("en-GB", { weekday: "long", day: "numeric", month: "long", year: "numeric" });
}

interface Props {
    bookedSlots: string[];
    settings: {
        booking_slots: string[];
        audit_fee_ngn: number;
        audit_fee_gbp: number;
        blackout_dates: string[];
    };
}

export default function Audit({ bookedSlots, settings }: Props) {
  const [step, setStep] = useState<"slot" | "details" | "done">("slot");
  const [monthCursor, setMonthCursor] = useState<Date>(() => {
    const d = new Date();
    return new Date(d.getFullYear(), d.getMonth(), 1);
  });
  const [selectedDate, setSelectedDate] = useState<Date | null>(null);
  const [selectedTime, setSelectedTime] = useState<string | null>(null);
  
  const { data, setData, post, processing, reset: resetForm, transform } = useForm({
    name: "",
    email: "",
    company: "",
    location: "",
    revenue_band: "",
    challenge: "",
    scheduled_at: "",
  });

  const bookedKeys = useMemo(() => new Set(bookedSlots), [bookedSlots]);
  const blackoutKeys = useMemo(() => new Set(settings.blackout_dates), [settings.blackout_dates]);

  const [confirmation, setConfirmation] = useState<{ date: Date; time: string; email: string } | null>(null);

  const today = useMemo(() => {
    const t = new Date();
    t.setHours(0, 0, 0, 0);
    return t;
  }, []);

  const calendarDays = useMemo(() => {
    const first = new Date(monthCursor.getFullYear(), monthCursor.getMonth(), 1);
    const startWeekday = (first.getDay() + 6) % 7; // Monday = 0
    const daysInMonth = new Date(monthCursor.getFullYear(), monthCursor.getMonth() + 1, 0).getDate();
    const cells: Array<Date | null> = [];
    for (let i = 0; i < startWeekday; i++) cells.push(null);
    for (let d = 1; d <= daysInMonth; d++) cells.push(new Date(monthCursor.getFullYear(), monthCursor.getMonth(), d));
    while (cells.length % 7 !== 0) cells.push(null);
    return cells;
  }, [monthCursor]);

  const monthLabel = monthCursor.toLocaleDateString("en-GB", { month: "long", year: "numeric" });

  const faqs = [
    { 
        q: "Is the free audit call actually free?", 
        a: `The 30-minute initial call is free. The full written Growth Audit Report (25 pages, 2-week delivery) is ₦${settings.audit_fee_ngn.toLocaleString()} / £${settings.audit_fee_gbp.toLocaleString()}. You book the free call first — and if after speaking to us you don't want to proceed, there's no charge for the call.` 
    },
    { q: "How quickly will I hear back?", a: "Immediately. Once you confirm a slot, you'll get a confirmation email with the date, time (WAT), a calendar invite link, and what to prepare." },
    { q: "What happens if the audit shows I'm not ready for a retainer?", a: "We tell you. Honestly. The report will show you exactly what to fix first — some of which you can do yourself. If we don't think a retainer is the right next step for your business yet, we'll say so and tell you when to come back." },
  ];

  function selectDate(d: Date) {
    setSelectedDate(d);
    setSelectedTime(null);
  }

  function canProceedToDetails() {
    return selectedDate && selectedTime;
  }

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!selectedDate || !selectedTime) return;
    
    const [hours, minutes] = selectedTime.split(':');
    const scheduledAt = new Date(selectedDate);
    scheduledAt.setHours(parseInt(hours), parseInt(minutes), 0, 0);

    transform((data) => ({
        ...data,
        scheduled_at: scheduledAt.toISOString(),
    }));

    post(route('audit.store'), {
        preserveScroll: true,
        onSuccess: () => {
            setConfirmation({ date: selectedDate, time: selectedTime, email: data.email });
            setStep("done");
        }
    });
  }

  function reset() {
    setStep("slot");
    setSelectedDate(null);
    setSelectedTime(null);
    resetForm();
    setConfirmation(null);
  }

  const prevMonthDisabled =
    monthCursor.getFullYear() === today.getFullYear() && monthCursor.getMonth() === today.getMonth();

  return (
    <AltivateLayout title="Book your Growth Audit" description="Pick a weekday slot and lock in your free 30-minute Growth Audit call.">
      <div>
        <section className="container-x pt-32 pb-24 md:pt-40 md:pb-32">
          <p className="eyebrow">Book a Growth Audit</p>
          <h1 className="font-display mt-6 max-w-5xl text-[clamp(2.5rem,7vw,5.5rem)] leading-[0.95]">
            Book your <span className="italic">Growth Audit.</span>
          </h1>
          <p className="mt-8 max-w-3xl text-lg text-muted-foreground">
            Pick a weekday slot below. In 30 minutes on a call, and two weeks of structured research, we will show you exactly what is holding your business back — and exactly what to do about it. Not a sales call. A diagnostic session.
          </p>

          <div className="mt-14 grid gap-px bg-border sm:grid-cols-3 rounded-3xl overflow-hidden border border-border">
            {stats.map((s) => (
              <div key={s.v} className="bg-background p-8">
                <div className="font-display text-6xl text-accent">{s.k}</div>
                <p className="mt-4 text-sm text-muted-foreground">{s.v}</p>
              </div>
            ))}
          </div>
        </section>

        {/* WHAT WE COVER */}
        <section className="border-y border-border bg-secondary/30">
          <div className="container-x py-20">
            <p className="eyebrow">What the audit covers</p>
            <h2 className="font-display mt-4 max-w-3xl text-4xl md:text-5xl leading-[1.05]">Six areas we examine in <span className="italic">every audit.</span></h2>

            <div className="mt-12 grid gap-px bg-border sm:grid-cols-2 lg:grid-cols-3 rounded-3xl overflow-hidden border border-border">
              {areas.map((a) => (
                <div key={a.n} className="bg-background p-8">
                  <div className="font-display text-4xl text-accent">{a.n}</div>
                  <h3 className="font-display mt-6 text-xl">{a.t}</h3>
                  <p className="mt-3 text-sm text-muted-foreground">{a.b}</p>
                </div>
              ))}
            </div>
          </div>
        </section>

        {/* BOOKING FLOW */}
        <section className="container-x py-14">
          <div className="grid gap-8 md:grid-cols-12">
            <div className="md:col-span-5">
              <p className="eyebrow">Booking</p>
              <h2 className="font-display mt-2 text-3xl md:text-4xl leading-[1.05]">
                {step === "done" ? <>Slot <span className="italic">confirmed.</span></> : <>Pick a <span className="italic">time</span> that works.</>}
              </h2>
              <p className="mt-3 text-sm text-muted-foreground">
                All times shown in West Africa Time (WAT). Slots run Monday–Friday.
              </p>

              <ol className="mt-5 space-y-2.5">
                <Step n={1} active={step === "slot"} done={step !== "slot"} label="Choose date and time" />
                <Step n={2} active={step === "details"} done={step === "done"} label="Add your details" />
                <Step n={3} active={step === "done"} done={step === "done"} label="Get confirmation email" />
              </ol>

              <div className="mt-6 space-y-2.5">
                <div>
                  <p className="eyebrow">Email</p>
                  <p className="font-display mt-0.5 text-lg">hello@altivatesolutions.com</p>
                </div>
                <div>
                  <p className="eyebrow">Locations</p>
                  <p className="font-display mt-0.5 text-lg">Lagos · London · New York</p>
                </div>
              </div>
            </div>

            <div className="md:col-span-7">
              <div className="rounded-2xl border border-border bg-card p-4 md:p-5">
                {step === "slot" && (
                  <div>
                    <div className="flex items-center justify-between">
                      <h3 className="font-display text-xl">{monthLabel}</h3>
                      <div className="flex items-center gap-2">
                        <button
                          type="button"
                          onClick={() => setMonthCursor(new Date(monthCursor.getFullYear(), monthCursor.getMonth() - 1, 1))}
                          disabled={prevMonthDisabled}
                          aria-label="Previous month"
                          className="flex h-8 w-8 items-center justify-center rounded-full border border-border disabled:opacity-30"
                        >
                          <ChevronLeft className="h-3.5 w-3.5" />
                        </button>
                        <button
                          type="button"
                          onClick={() => setMonthCursor(new Date(monthCursor.getFullYear(), monthCursor.getMonth() + 1, 1))}
                          aria-label="Next month"
                          className="flex h-8 w-8 items-center justify-center rounded-full border border-border"
                        >
                          <ChevronRight className="h-3.5 w-3.5" />
                        </button>
                      </div>
                    </div>

                    <div className="mt-2 grid grid-cols-7 gap-1 text-center text-[10px] uppercase tracking-wider text-muted-foreground">
                      {["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"].map((d) => (
                        <div key={d} className="py-0">{d}</div>
                      ))}
                    </div>

                    <div className="mt-0.5 grid grid-cols-7 gap-0.5">
                      {calendarDays.map((d, idx) => {
                        if (!d) return <div key={idx} className="h-8" />;
                        const isPast = d < today;
                        const weekday = isWeekday(d);
                        const k = dateKey(d);
                        const isBlackout = blackoutKeys.has(k);
                        const disabled = isPast || !weekday || isBlackout;
                        
                        const allBooked = settings.booking_slots.every((t) => bookedKeys.has(`${k}|${t}`));
                        const isSelected = selectedDate && dateKey(selectedDate) === k;
                        const isToday = dateKey(today) === k;

                        return (
                          <button
                            key={idx}
                            type="button"
                            onClick={() => !disabled && !allBooked && selectDate(d)}
                            disabled={disabled || allBooked}
                            className={`h-8 rounded-md text-[11px] transition-colors ${
                              isSelected
                                ? "bg-primary text-primary-foreground"
                                : disabled || allBooked
                                ? "text-muted-foreground/40 line-through cursor-not-allowed"
                                : "hover:bg-secondary"
                            } ${isToday && !isSelected ? "ring-1 ring-accent" : ""}`}
                          >
                            {d.getDate()}
                          </button>
                        );
                      })}
                    </div>

                    <div className="mt-3">
                      <p className="eyebrow">Available times</p>
                      {selectedDate ? (
                        <div className="mt-2 grid grid-cols-2 gap-1.5 sm:grid-cols-4">
                          {settings.booking_slots.map((t) => {
                            const key = `${dateKey(selectedDate)}|${t}`;
                            const taken = bookedKeys.has(key);
                            const active = selectedTime === t;
                            return (
                              <button
                                key={t}
                                type="button"
                                onClick={() => !taken && setSelectedTime(t)}
                                disabled={taken}
                                className={`h-8 rounded-full border text-[11px] transition-colors ${
                                  active
                                    ? "border-primary bg-primary text-primary-foreground"
                                    : taken
                                    ? "border-border text-muted-foreground/50 line-through cursor-not-allowed"
                                    : "border-border hover:border-primary"
                                }`}
                              >
                                {t}
                              </button>
                            );
                          })}
                        </div>
                      ) : (
                        <p className="mt-3 text-sm text-muted-foreground">Select a weekday on the calendar to see open slots.</p>
                      )}
                    </div>

                    <div className="mt-5 flex items-center justify-between gap-4">
                      <p className="text-xs text-muted-foreground">
                        {selectedDate && selectedTime
                          ? `${formatLongDate(selectedDate)} · ${selectedTime} WAT`
                          : "No slot selected yet."}
                      </p>
                      <button
                        type="button"
                        onClick={() => canProceedToDetails() && setStep("details")}
                        disabled={!canProceedToDetails()}
                        className="inline-flex h-9 items-center gap-2 rounded-full bg-primary px-5 text-xs font-medium text-primary-foreground transition-transform hover:-translate-y-0.5 disabled:cursor-not-allowed disabled:opacity-40"
                      >
                        Continue <ArrowUpRight className="h-4 w-4" />
                      </button>
                    </div>
                  </div>
                )}

                {step === "details" && selectedDate && selectedTime && (
                  <form onSubmit={handleSubmit} className="space-y-4">
                    <div className="flex items-center gap-3 rounded-xl border border-border bg-secondary/40 p-2.5">
                      <CalendarClock className="h-3.5 w-3.5 text-accent" />
                      <div className="text-[11px]">
                        <p className="font-medium text-ink leading-tight">{formatLongDate(selectedDate)}</p>
                        <p className="text-muted-foreground leading-tight">{selectedTime} WAT · 30 mins</p>
                      </div>
                      <button
                        type="button"
                        onClick={() => setStep("slot")}
                        className="ml-auto text-xs underline underline-offset-4 hover:text-accent"
                      >
                        Change
                      </button>
                    </div>

                    <div className="grid gap-4 sm:grid-cols-2">
                      <Field label="Your full name" name="name" placeholder="Adaeze Okonkwo" value={data.name} onChange={(v) => setData('name', v)} required />
                      <Field label="Your email address" name="email" type="email" placeholder="you@business.com" value={data.email} onChange={(v) => setData('email', v)} required />
                    </div>
                    <Field label="Your business name" name="company" placeholder="Business Ltd." value={data.company} onChange={(v) => setData('company', v)} />

                    <div>
                      <label className="eyebrow block">Where are you based?</label>
                      <div className="mt-2.5 grid grid-cols-2 gap-2 sm:grid-cols-4">
                        {locations.map((l) => (
                          <label key={l} className="flex h-8 cursor-pointer items-center justify-center rounded-full border border-border text-[11px] has-[:checked]:border-primary has-[:checked]:bg-primary has-[:checked]:text-primary-foreground transition-all">
                            <input
                              type="radio"
                              name="location"
                              value={l}
                              checked={data.location === l}
                              onChange={() => setData('location', l)}
                              className="sr-only"
                            />
                            {l}
                          </label>
                        ))}
                      </div>
                    </div>

                    <div>
                      <label className="eyebrow block" htmlFor="rev">Approximate annual revenue</label>
                      <div className="mt-2.5">
                        <Select 
                          value={data.revenue_band} 
                          onValueChange={(val) => setData('revenue_band', val)}
                        >
                          <SelectTrigger className="w-full h-11 rounded-full border border-border bg-background px-5 text-[13px] outline-none focus:ring-2 focus:ring-primary/20 transition-all text-left">
                            <SelectValue placeholder="Select a revenue band" />
                          </SelectTrigger>
                          <SelectContent className="bg-white border-border rounded-2xl shadow-xl">
                            {revenues.map((r) => (
                              <SelectItem key={r} value={r} className="text-[13px] py-2.5">{r}</SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>
                    </div>

                    <div>
                      <label className="eyebrow block" htmlFor="msg">What is your biggest marketing challenge right now?</label>
                      <textarea
                        id="msg"
                        name="challenge"
                        rows={3}
                        value={data.challenge}
                        onChange={(e) => setData('challenge', e.target.value)}
                        placeholder="One or two sentences."
                        className="mt-2.5 w-full rounded-xl border border-border bg-background p-3 text-xs outline-none focus:border-primary transition-all"
                      />
                    </div>

                    <div className="flex items-center justify-between gap-4">
                      <button type="button" onClick={() => setStep("slot")} className="text-sm underline underline-offset-4 hover:text-accent">
                        Back to calendar
                      </button>
                      <button
                        type="submit"
                        disabled={processing}
                        className="inline-flex h-9 items-center gap-2 rounded-full bg-primary px-5 text-xs font-medium text-primary-foreground transition-transform hover:-translate-y-0.5"
                      >
                        {processing ? 'Confirming...' : 'Confirm'} <ArrowUpRight className="h-3.5 w-3.5" />
                      </button>
                    </div>
                    <p className="text-xs text-muted-foreground">
                      Free · 30 minutes · No obligation · Confirmation email sent immediately
                    </p>
                  </form>
                )}

                {step === "done" && confirmation && (
                  <div className="py-8 text-center">
                    <div className="mx-auto flex h-14 w-14 items-center justify-center rounded-full bg-accent">
                      <Check className="h-6 w-6 text-accent-foreground" />
                    </div>
                    <h3 className="font-display mt-6 text-3xl">Your slot is locked in.</h3>
                    <div className="mx-auto mt-6 max-w-sm rounded-2xl border border-border bg-secondary/40 p-5 text-left">
                      <div className="flex items-center gap-3">
                        <CalendarClock className="h-5 w-5 text-accent" />
                        <div className="text-sm">
                          <p className="font-medium">{formatLongDate(confirmation.date)}</p>
                          <p className="text-muted-foreground">{confirmation.time} WAT · 30 minutes</p>
                        </div>
                      </div>
                    </div>
                    <p className="mt-6 inline-flex items-center gap-2 text-sm text-muted-foreground">
                      <Mail className="h-4 w-4" /> Confirmation sent to <span className="text-foreground">{confirmation.email}</span>
                    </p>
                    <p className="mt-2 text-xs text-muted-foreground">
                      Check your inbox for the calendar invite and a short prep checklist.
                    </p>
                    <button
                      type="button"
                      onClick={reset}
                      className="mt-8 inline-flex h-11 items-center gap-2 rounded-full border border-border px-5 text-sm hover:border-primary"
                    >
                      Book another slot
                    </button>
                  </div>
                )}
              </div>
            </div>
          </div>
        </section>

        {/* REASSURANCE FAQ */}
        <section className="container-x pb-24">
          <p className="eyebrow">Still unsure?</p>
          <h2 className="font-display mt-4 max-w-3xl text-4xl md:text-5xl leading-[1.05]">Here's what past clients ask before the call.</h2>
          <div className="mt-12 grid gap-6 md:grid-cols-3">
            {faqs.map((f) => (
              <div key={f.q} className="rounded-2xl border border-border bg-card p-6">
                <h3 className="font-display text-lg">{f.q}</h3>
                <p className="mt-3 text-sm text-muted-foreground">{f.a}</p>
              </div>
            ))}
          </div>
        </section>
      </div>
    </AltivateLayout>
  );
}

function Step({ n, active, done, label }: { n: number; active: boolean; done: boolean; label: string }) {
  return (
    <li className="flex items-center gap-4">
      <span
        className={`flex h-9 w-9 items-center justify-center rounded-full border text-sm font-medium ${
          done ? "border-accent bg-accent text-accent-foreground" : active ? "border-primary bg-primary text-primary-foreground" : "border-border text-muted-foreground"
        }`}
      >
        {done ? <Check className="h-4 w-4" /> : n}
      </span>
      <span className={`text-sm ${active || done ? "text-foreground" : "text-muted-foreground"}`}>{label}</span>
    </li>
  );
}

function Field({
  label,
  name,
  type = "text",
  placeholder,
  value,
  onChange,
  required,
}: {
  label: string;
  name: string;
  type?: string;
  placeholder?: string;
  value: string;
  onChange: (v: string) => void;
  required?: boolean;
}) {
  return (
    <div>
      <label className="eyebrow block" htmlFor={name}>{label}</label>
      <input
        id={name}
        name={name}
        type={type}
        required={required}
        placeholder={placeholder}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        className="mt-1.5 h-9 w-full rounded-full border border-border bg-background px-4 text-xs outline-none focus:border-primary transition-all"
      />
    </div>
  );
}
