"use client";

import { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Mail, Phone, MapPin, Clock, Send, Loader2, MessageSquare, ShieldCheck, CheckCircle2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { useToast } from "@/hooks/use-toast";
import { SectionHeading } from "./section-heading";
import { Reveal } from "./reveal";
import { COMPANY, SERVICES } from "./site-data";

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(),
  company: z.string().optional(),
  service: z.string().optional(),
  message: z.string().min(10, "Please provide a few more details about your project"),
});

type FormValues = z.infer<typeof schema>;

const CONTACT_INFO = [
  {
    icon: Mail,
    label: "Email Inquiry",
    value: COMPANY.email,
    href: `mailto:${COMPANY.email}`,
  },
  {
    icon: Phone,
    label: "Direct Phone",
    value: COMPANY.phone,
    href: `tel:${COMPANY.phone.replace(/[^+\d]/g, "")}`,
  },
  {
    icon: MapPin,
    label: "Headquarters",
    value: COMPANY.address,
    href: "#",
  },
  {
    icon: Clock,
    label: "Office Hours",
    value: COMPANY.hours,
    href: "#",
  },
];

export function Contact() {
  const { toast } = useToast();
  const [submitting, setSubmitting] = useState(false);
  const [sentSuccess, setSentSuccess] = useState(false);

  const {
    register,
    handleSubmit,
    setValue,
    watch,
    reset,
    formState: { errors },
  } = useForm<FormValues>({
    resolver: zodResolver(schema),
    defaultValues: {
      name: "",
      email: "",
      phone: "",
      company: "",
      service: "",
      message: "",
    },
  });

  const selectedService = watch("service");

  const onSubmit = async (values: FormValues) => {
    setSubmitting(true);
    try {
      const res = await fetch("/api/contact", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(values),
      });
      const data = await res.json();
      if (!res.ok || !data.ok) {
        throw new Error(data.error || "Failed to send message");
      }
      setSentSuccess(true);
      toast({
        title: "RFQ Proposal Request Received",
        description: "Our senior engineering consultant will review your scope and respond within 24 hours.",
      });
      reset();
    } catch (err) {
      toast({
        variant: "destructive",
        title: "Could not send message",
        description:
          err instanceof Error ? err.message : "Please try again later.",
      });
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <section id="contact" className="section-pad bg-muted/40">
      <div className="mx-auto max-w-7xl px-4 md:px-6">
        <SectionHeading
          eyebrow="Get In Touch"
          title="Let's build your next project together"
          description="Have an infrastructure tender, feasibility requirement, or construction RFQ? Request a technical proposal or consult directly with our engineering team."
        />

        <div className="mt-14 grid gap-8 lg:grid-cols-5">
          {/* Contact Info Card */}
          <Reveal className="lg:col-span-2">
            <div className="flex h-full flex-col justify-between rounded-xl border border-border bg-card p-7 shadow-lg">
              <div>
                <span className="text-xs font-bold uppercase tracking-[0.2em] text-primary">
                  Official Communication
                </span>
                <h3 className="mt-3 text-2xl font-extrabold text-foreground">
                  Connect with {COMPANY.shortName}
                </h3>
                <p className="mt-2 text-xs leading-relaxed text-muted-foreground">
                  Our engineering team is ready to discuss civil tenders, hydropower plans, highway contracts, and equipment deployment nationwide.
                </p>

                <div className="mt-8 space-y-5">
                  {CONTACT_INFO.map((info) => {
                    const Icon = info.icon;
                    return (
                      <a
                        key={info.label}
                        href={info.href}
                        className="group flex items-start gap-4"
                      >
                        <span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg border border-border bg-background text-primary transition-colors group-hover:border-primary/40 group-hover:bg-primary group-hover:text-primary-foreground">
                          <Icon className="h-4 w-4" strokeWidth={1.5} />
                        </span>
                        <div>
                          <div className="text-[10px] font-bold uppercase tracking-[0.14em] text-muted-foreground">
                            {info.label}
                          </div>
                          <div className="mt-0.5 text-xs font-bold text-foreground">
                            {info.value}
                          </div>
                        </div>
                      </a>
                    );
                  })}
                </div>

                {/* Instant WhatsApp Connect */}
                <div className="mt-8 rounded-lg border border-emerald-500/30 bg-emerald-500/10 p-4">
                  <div className="flex items-center gap-2 font-bold text-xs text-emerald-600 dark:text-emerald-400">
                    <MessageSquare className="h-4 w-4" />
                    Instant Engineering WhatsApp Consult
                  </div>
                  <p className="mt-1 text-[11px] text-muted-foreground">
                    Connect directly with an engineer on site for urgent equipment deployment or site inquiries.
                  </p>
                  <Button asChild size="sm" className="mt-3 w-full h-8 text-xs bg-emerald-600 hover:bg-emerald-700 text-white font-semibold">
                    <a href={`https://wa.me/${COMPANY.whatsapp.replace(/[^+\d]/g, "")}`} target="_blank" rel="noreferrer">
                      Open WhatsApp Chat
                    </a>
                  </Button>
                </div>
              </div>

              <div className="pt-6 border-t border-border mt-6 text-[11px] text-muted-foreground flex items-center justify-between">
                <div>
                  <span className="font-bold text-foreground">{COMPANY.name}</span>
                  <br />
                  Reg. No. {COMPANY.registrationNo}
                </div>
                <ShieldCheck className="h-5 w-5 text-primary shrink-0" />
              </div>
            </div>
          </Reveal>

          {/* Form */}
          <Reveal delay={0.1} className="lg:col-span-3">
            <div className="rounded-xl border border-border bg-card p-7 shadow-lg">
              {sentSuccess ? (
                <div className="py-12 text-center space-y-4">
                  <div className="mx-auto flex h-14 w-14 items-center justify-center rounded-full bg-emerald-500/20 text-emerald-500">
                    <CheckCircle2 className="h-8 w-8" />
                  </div>
                  <h3 className="text-xl font-bold text-foreground">Inquiry Received Successfully</h3>
                  <p className="text-xs text-muted-foreground max-w-md mx-auto">
                    Thank you for contacting {COMPANY.name}. Our technical team is reviewing your project parameters and will contact you shortly.
                  </p>
                  <Button onClick={() => setSentSuccess(false)} variant="outline" size="sm" className="mt-4">
                    Send Another Request
                  </Button>
                </div>
              ) : (
                <form onSubmit={handleSubmit(onSubmit)}>
                  <div className="flex items-center justify-between border-b border-border pb-4 mb-5">
                    <div>
                      <h3 className="text-lg font-bold text-foreground">Technical Proposal & RFQ Form</h3>
                      <p className="text-xs text-muted-foreground">Fill in your requirements to receive a formal scope assessment.</p>
                    </div>
                    <span className="rounded-full bg-primary/10 px-2.5 py-1 text-[10px] font-extrabold text-primary uppercase">
                      Official RFQ
                    </span>
                  </div>

                  <div className="grid gap-5 sm:grid-cols-2">
                    <div className="space-y-1.5">
                      <Label htmlFor="name" className="text-xs font-semibold">
                        Full Name <span className="text-primary">*</span>
                      </Label>
                      <Input
                        id="name"
                        placeholder="e.g. Er. Ramesh Adhikari"
                        {...register("name")}
                        aria-invalid={!!errors.name}
                      />
                      {errors.name && (
                        <p className="text-[11px] text-destructive">{errors.name.message}</p>
                      )}
                    </div>

                    <div className="space-y-1.5">
                      <Label htmlFor="email" className="text-xs font-semibold">
                        Email Address <span className="text-primary">*</span>
                      </Label>
                      <Input
                        id="email"
                        type="email"
                        placeholder="name@organization.com"
                        {...register("email")}
                        aria-invalid={!!errors.email}
                      />
                      {errors.email && (
                        <p className="text-[11px] text-destructive">{errors.email.message}</p>
                      )}
                    </div>

                    <div className="space-y-1.5">
                      <Label htmlFor="phone" className="text-xs font-semibold">Contact Phone</Label>
                      <Input
                        id="phone"
                        placeholder="+977-98XXXXXXXX"
                        {...register("phone")}
                      />
                    </div>

                    <div className="space-y-1.5">
                      <Label htmlFor="company" className="text-xs font-semibold">Company / Organization</Label>
                      <Input
                        id="company"
                        placeholder="Organization or Ministry"
                        {...register("company")}
                      />
                    </div>
                  </div>

                  <div className="mt-4 space-y-1.5">
                    <Label htmlFor="service" className="text-xs font-semibold">Primary Engineering Service</Label>
                    <Select
                      value={selectedService}
                      onValueChange={(v) => setValue("service", v)}
                    >
                      <SelectTrigger id="service" className="w-full">
                        <SelectValue placeholder="Select primary engineering domain" />
                      </SelectTrigger>
                      <SelectContent className="max-h-72">
                        {SERVICES.map((s) => (
                          <SelectItem key={s.title} value={s.title}>
                            {s.title}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>

                  <div className="mt-4 space-y-1.5">
                    <Label htmlFor="message" className="text-xs font-semibold">
                      Project Details & Requirements <span className="text-primary">*</span>
                    </Label>
                    <Textarea
                      id="message"
                      rows={4}
                      placeholder="Specify project scope, location in Nepal, estimated timelines, or required machinery..."
                      {...register("message")}
                      aria-invalid={!!errors.message}
                    />
                    {errors.message && (
                      <p className="text-[11px] text-destructive">{errors.message.message}</p>
                    )}
                  </div>

                  <Button
                    type="submit"
                    size="lg"
                    disabled={submitting}
                    className="mt-6 h-11 w-full text-sm font-semibold shadow-md shadow-primary/20"
                  >
                    {submitting ? (
                      <>
                        <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                        Submitting RFQ Proposal...
                      </>
                    ) : (
                      <>
                        Submit RFQ Proposal Request
                        <Send className="ml-2 h-4 w-4" />
                      </>
                    )}
                  </Button>
                </form>
              )}
            </div>
          </Reveal>
        </div>
      </div>
    </section>
  );
}
