import { useState } from "react";
import { useSearchParams, Link } from "react-router-dom";
import { ArrowRight, Mail, Phone, Send, CheckCircle } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import Navbar from "@/components/Navbar";
import Footer from "@/components/Footer";
import { z } from "zod";
import { getPartnerCode } from "@/hooks/use-partner-code";

// ─── Validation schema ────────────────────────────────────────────────────────
const contactSchema = z.object({
  name: z
    .string()
    .trim()
    .min(1, "Name is required")
    .max(100, "Name must be under 100 characters"),
  email: z
    .string()
    .trim()
    .email("Please enter a valid email address")
    .max(255, "Email must be under 255 characters"),
  phone: z
    .string()
    .trim()
    .max(30, "Phone number must be under 30 characters")
    .optional()
    .or(z.literal("")),
  comment: z
    .string()
    .trim()
    .min(1, "Please enter a message")
    .max(2000, "Message must be under 2000 characters"),
});

type ContactForm = z.infer<typeof contactSchema>;
type FormErrors = Partial<Record<keyof ContactForm, string>>;

// ─── Page ─────────────────────────────────────────────────────────────────────
const Contact = () => {
  const [searchParams] = useSearchParams();
  const prefillQuestion = searchParams.get("question") ?? "";

  const [form, setForm] = useState<ContactForm>({
    name: "",
    email: "",
    phone: "",
    comment: prefillQuestion,
  });
  const [errors, setErrors] = useState<FormErrors>({});
  const [submitted, setSubmitted] = useState(false);

  const handleChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
  ) => {
    const { name, value } = e.target;
    setForm((prev) => ({ ...prev, [name]: value }));
    // Clear field error on change
    if (errors[name as keyof ContactForm]) {
      setErrors((prev) => ({ ...prev, [name]: undefined }));
    }
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const result = contactSchema.safeParse(form);
    if (!result.success) {
      const fieldErrors: FormErrors = {};
      result.error.errors.forEach((err) => {
        const field = err.path[0] as keyof ContactForm;
        if (!fieldErrors[field]) fieldErrors[field] = err.message;
      });
      setErrors(fieldErrors);
      return;
    }
    setErrors({});
    const payload = { ...result.data, partnerCode: getPartnerCode() };
    console.log("Contact form submitted:", payload);
    setSubmitted(true);
  };

  return (
    <div className="min-h-screen bg-background">
      <Navbar />
      <main className="pt-24 pb-20">
        {/* Header */}
        <section className="max-w-2xl mx-auto px-4 sm:px-6 lg:px-8 text-center mb-12">
          <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full border border-primary/30 bg-primary/10 mb-4">
            <Mail className="w-3 h-3 text-primary" />
            <span className="text-xs font-semibold text-primary">Contact Us</span>
          </div>
          <h1 className="font-display font-bold text-4xl sm:text-5xl text-foreground mb-4">
            We'd love to hear from you
          </h1>
          <p className="text-muted-foreground text-lg">
            Ask us anything. We typically respond within a few hours.
          </p>
        </section>

        {/* Form card */}
        <section className="max-w-xl mx-auto px-4 sm:px-6 lg:px-8">
          {submitted ? (
            /* ── Success state ── */
            <div className="rounded-2xl border border-border bg-card p-10 text-center">
              <div className="w-14 h-14 rounded-full bg-primary/10 flex items-center justify-center mx-auto mb-5">
                <CheckCircle className="w-7 h-7 text-primary" />
              </div>
              <h2 className="font-display font-bold text-2xl text-foreground mb-3">
                Message sent!
              </h2>
              <p className="text-muted-foreground mb-2">
                Thanks,{" "}
                <span className="text-foreground font-medium">{form.name}</span>.
                We've received your message and will be in touch at{" "}
                <span className="text-foreground font-medium">{form.email}</span>.
              </p>
              <p className="text-sm text-muted-foreground mb-8">
                We usually respond within a few hours during business days.
              </p>
              <div className="flex flex-col sm:flex-row gap-3 justify-center">
                <Button asChild variant="outline" className="font-semibold">
                  <Link to="/faq">Browse FAQ</Link>
                </Button>
                <Button
                  asChild
                  className="bg-primary text-primary-foreground hover:bg-primary/90 font-semibold"
                >
                  <Link to="/signup">
                    Start Free Trial <ArrowRight className="w-4 h-4" />
                  </Link>
                </Button>
              </div>
            </div>
          ) : (
            /* ── Form ── */
            <div className="rounded-2xl border border-border bg-card p-8 shadow-sm">
              {prefillQuestion && (
                <div className="mb-6 p-3.5 rounded-xl bg-primary/10 border border-primary/20">
                  <p className="text-xs text-primary font-semibold mb-1">Your question</p>
                  <p className="text-sm text-foreground leading-relaxed">{prefillQuestion}</p>
                </div>
              )}

              <form onSubmit={handleSubmit} className="space-y-5" noValidate>
                {/* Name */}
                <div className="space-y-1.5">
                  <Label htmlFor="name">
                    Full Name <span className="text-primary">*</span>
                  </Label>
                  <Input
                    id="name"
                    name="name"
                    placeholder="Jane Smith"
                    value={form.name}
                    onChange={handleChange}
                    maxLength={100}
                    className="bg-secondary border-border focus:border-primary"
                    aria-invalid={!!errors.name}
                  />
                  {errors.name && (
                    <p className="text-xs text-destructive mt-1">{errors.name}</p>
                  )}
                </div>

                {/* Email */}
                <div className="space-y-1.5">
                  <Label htmlFor="email">
                    Work Email <span className="text-primary">*</span>
                  </Label>
                  <Input
                    id="email"
                    name="email"
                    type="email"
                    placeholder="jane@acmeindustrial.com"
                    value={form.email}
                    onChange={handleChange}
                    maxLength={255}
                    className="bg-secondary border-border focus:border-primary"
                    aria-invalid={!!errors.email}
                  />
                  {errors.email && (
                    <p className="text-xs text-destructive mt-1">{errors.email}</p>
                  )}
                </div>

                {/* Phone */}
                <div className="space-y-1.5">
                  <Label htmlFor="phone" className="flex items-center gap-1.5">
                    <Phone className="w-3.5 h-3.5 text-muted-foreground" />
                    Phone Number{" "}
                    <span className="text-xs text-muted-foreground font-normal">(optional)</span>
                  </Label>
                  <Input
                    id="phone"
                    name="phone"
                    type="tel"
                    placeholder="+1 (555) 000-0000"
                    value={form.phone}
                    onChange={handleChange}
                    maxLength={30}
                    className="bg-secondary border-border focus:border-primary"
                    aria-invalid={!!errors.phone}
                  />
                  {errors.phone && (
                    <p className="text-xs text-destructive mt-1">{errors.phone}</p>
                  )}
                </div>

                {/* Comment */}
                <div className="space-y-1.5">
                  <Label htmlFor="comment">
                    Message <span className="text-primary">*</span>
                  </Label>
                  <Textarea
                    id="comment"
                    name="comment"
                    placeholder="Tell us what you're looking for or ask your question here…"
                    value={form.comment}
                    onChange={handleChange}
                    maxLength={2000}
                    rows={5}
                    className="bg-secondary border-border focus:border-primary resize-none"
                    aria-invalid={!!errors.comment}
                  />
                  <div className="flex justify-between items-center">
                    {errors.comment ? (
                      <p className="text-xs text-destructive">{errors.comment}</p>
                    ) : (
                      <span />
                    )}
                    <p className="text-xs text-muted-foreground ml-auto">
                      {form.comment.length}/2000
                    </p>
                  </div>
                </div>

                <Button
                  type="submit"
                  size="lg"
                  className="w-full bg-primary text-primary-foreground hover:bg-primary/90 font-semibold glow-teal-sm"
                >
                  Send Message <Send className="w-4 h-4" />
                </Button>

                <p className="text-center text-xs text-muted-foreground">
                  We'll reply to your work email within a few hours.
                </p>
              </form>
            </div>
          )}
        </section>
      </main>
      <Footer />
    </div>
  );
};

export default Contact;
