import { useState, useMemo, FormEvent } from "react";
import { Link } from "react-router-dom";
import { ArrowLeft, CheckCircle } from "lucide-react";
import { z } from "zod";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import Navbar from "@/components/Navbar";
import Footer from "@/components/Footer";
import { getPartnerCode } from "@/hooks/use-partner-code";

const TIMEZONES = [
  "America/New_York",
  "America/Chicago",
  "America/Denver",
  "America/Los_Angeles",
  "America/Anchorage",
  "Pacific/Honolulu",
  "America/Toronto",
  "America/Vancouver",
  "Europe/London",
  "Europe/Berlin",
  "Europe/Paris",
  "Asia/Dubai",
  "Asia/Kolkata",
  "Asia/Singapore",
  "Asia/Tokyo",
  "Australia/Sydney",
];

const formSchema = z.object({
  firstName: z.string().trim().min(1, "First name is required").max(50),
  lastName: z.string().trim().min(1, "Last name is required").max(50),
  email: z.string().trim().email("Please enter a valid business email").max(255),
  timezone: z.string().min(1, "Please select a timezone"),
  captcha: z.string(),
});

function generateCaptcha() {
  const a = Math.floor(Math.random() * 10) + 1;
  const b = Math.floor(Math.random() * 10) + 1;
  return { question: `What is ${a} + ${b}?`, answer: a + b };
}

const AdminDemoRequest = () => {
  const [captcha, setCaptcha] = useState(() => generateCaptcha());
  const [formData, setFormData] = useState({ firstName: "", lastName: "", email: "", timezone: "", captcha: "" });
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [submitted, setSubmitted] = useState(false);

  const handleSubmit = (e: FormEvent) => {
    e.preventDefault();
    setErrors({});

    const result = formSchema.safeParse(formData);
    if (!result.success) {
      const fieldErrors: Record<string, string> = {};
      result.error.errors.forEach((err) => {
        if (err.path[0]) fieldErrors[err.path[0] as string] = err.message;
      });
      setErrors(fieldErrors);
      return;
    }

    if (parseInt(formData.captcha) !== captcha.answer) {
      setErrors({ captcha: "Incorrect answer. Please try again." });
      setCaptcha(generateCaptcha());
      setFormData((prev) => ({ ...prev, captcha: "" }));
      return;
    }

    const payload = { ...result.data, partnerCode: getPartnerCode() };
    console.log("Admin demo request submitted:", payload);
    setSubmitted(true);
  };

  const updateField = (field: string, value: string) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
    if (errors[field]) setErrors((prev) => { const n = { ...prev }; delete n[field]; return n; });
  };

  if (submitted) {
    return (
      <div className="min-h-screen bg-background">
        <Navbar />
        <main className="pt-28 pb-20">
          <div className="max-w-md mx-auto px-4 text-center">
            <div className="w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center mx-auto mb-6">
              <CheckCircle className="w-8 h-8 text-primary" />
            </div>
            <h1 className="font-display font-bold text-2xl text-foreground mb-3">Request Received!</h1>
            <p className="text-muted-foreground mb-6">We'll reach out to schedule your admin dashboard demo shortly.</p>
            <Button asChild variant="outline">
              <Link to="/demo"><ArrowLeft className="w-4 h-4" /> Back to Demo</Link>
            </Button>
          </div>
        </main>
        <Footer />
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-background">
      <Navbar />
      <main className="pt-28 pb-20">
        <div className="max-w-md mx-auto px-4">
          <Button asChild variant="ghost" size="sm" className="mb-6 text-muted-foreground">
            <Link to="/demo"><ArrowLeft className="w-4 h-4" /> Back to Demo</Link>
          </Button>

          <h1 className="font-display font-bold text-2xl text-foreground mb-2">Request Admin Demo</h1>
          <p className="text-muted-foreground text-sm mb-8">Fill in your details and we'll schedule a personalized walkthrough of the admin dashboard.</p>

          <form onSubmit={handleSubmit} className="space-y-5">
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="firstName">First Name</Label>
                <Input id="firstName" value={formData.firstName} onChange={(e) => updateField("firstName", e.target.value)} placeholder="Jane" />
                {errors.firstName && <p className="text-xs text-destructive">{errors.firstName}</p>}
              </div>
              <div className="space-y-2">
                <Label htmlFor="lastName">Last Name</Label>
                <Input id="lastName" value={formData.lastName} onChange={(e) => updateField("lastName", e.target.value)} placeholder="Smith" />
                {errors.lastName && <p className="text-xs text-destructive">{errors.lastName}</p>}
              </div>
            </div>

            <div className="space-y-2">
              <Label htmlFor="email">Business Email</Label>
              <Input id="email" type="email" value={formData.email} onChange={(e) => updateField("email", e.target.value)} placeholder="jane@company.com" />
              {errors.email && <p className="text-xs text-destructive">{errors.email}</p>}
            </div>

            <div className="space-y-2">
              <Label>Timezone</Label>
              <Select value={formData.timezone} onValueChange={(v) => updateField("timezone", v)}>
                <SelectTrigger><SelectValue placeholder="Select your timezone" /></SelectTrigger>
                <SelectContent>
                  {TIMEZONES.map((tz) => (
                    <SelectItem key={tz} value={tz}>{tz.replace(/_/g, " ")}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
              {errors.timezone && <p className="text-xs text-destructive">{errors.timezone}</p>}
            </div>

            <div className="space-y-2">
              <Label htmlFor="captcha">{captcha.question}</Label>
              <Input id="captcha" value={formData.captcha} onChange={(e) => updateField("captcha", e.target.value)} placeholder="Your answer" inputMode="numeric" />
              {errors.captcha && <p className="text-xs text-destructive">{errors.captcha}</p>}
            </div>

            <Button type="submit" size="lg" className="w-full bg-primary text-primary-foreground hover:bg-teal-glow font-semibold glow-teal-sm">
              Submit Request
            </Button>
          </form>
        </div>
      </main>
      <Footer />
    </div>
  );
};

export default AdminDemoRequest;
