import Navbar from "@/components/Navbar";
import Footer from "@/components/Footer";
import SeoHead from "@/components/SeoHead";
import { Button } from "@/components/ui/button";
import { MapPin, Phone, Mail, Clock, Send } from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";

const csrfToken = () => (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement | null)?.content ?? '';

const useTenant = () => ({ isTenantMode: false, subdomain: null, isLoading: false, branding: null as any, companyName: null as string | null });

const ContactPage = () => {
  const { isTenantMode, branding, companyName } = useTenant();
  const [formData, setFormData] = useState({ name: "", email: "", phone: "", subject: "", message: "" });
  const [sending, setSending] = useState(false);

  // Contact page always uses light theme in tenant mode — branding only applies to the homepage/header
  const brandingStyles = {} as React.CSSProperties;

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (isTenantMode && branding?.contact_email) {
      setSending(true);
      try {
        const res = await fetch("/api/functions/send-contact-form", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "X-CSRF-TOKEN": csrfToken(),
          },
          body: JSON.stringify({
            to: branding.contact_email,
            from_name: formData.name,
            from_email: formData.email,
            phone: formData.phone,
            subject: formData.subject,
            message: formData.message,
            company_name: companyName || "White-Label Tenant",
          }),
        });
        if (!res.ok) {
          const err = await res.json().catch(() => ({}));
          throw new Error(err.message || "Failed to send message");
        }
        toast.success("Message sent! We'll be in touch shortly.");
        setFormData({ name: "", email: "", phone: "", subject: "", message: "" });
      } catch (err: any) {
        toast.error(err.message || "Failed to send message. Please try again.");
      } finally {
        setSending(false);
      }
    } else {
      alert("Thank you for your message. We'll be in touch shortly!");
      setFormData({ name: "", email: "", phone: "", subject: "", message: "" });
    }
  };

  const contactInfo = isTenantMode
    ? [
        ...(branding?.contact_address ? [{ icon: MapPin, title: "Address", lines: [branding.contact_address] }] : []),
        ...(branding?.contact_phone ? [{ icon: Phone, title: "Phone", lines: [branding.contact_phone] }] : []),
        ...(branding?.contact_email ? [{ icon: Mail, title: "Email", lines: [branding.contact_email] }] : []),
        ...(branding?.opening_hours ? [{ icon: Clock, title: "Opening Hours", lines: [branding.opening_hours] }] : []),
      ]
    : [
        { icon: MapPin, title: "Address", lines: ["1C Simpson Parkway", "Kirkton Campus", "Livingston", "EH54 7BH"] },
        { icon: Phone, title: "Phone", lines: ["0131 549 9071"] },
        { icon: Mail, title: "Email", lines: ["info@utilitytrainingcentre.co.uk"] },
        { icon: Clock, title: "Opening Hours", lines: ["Monday - Friday: 8:00 AM - 6:00 PM", "Saturday: 9:00 AM - 1:00 PM"] },
      ];

  return (
    <div className={`min-h-screen bg-background${isTenantMode ? " tenant-light" : ""}`}>
      <SeoHead />
      <Navbar />
      <div className="pt-24 pb-24">
        <div className="container mx-auto px-4 mb-12">
          <h1 className="text-4xl md:text-5xl font-bold text-foreground mb-3">Contact Us</h1>
          <p className="text-muted-foreground max-w-2xl">
            {isTenantMode
              ? `Get in touch with ${companyName || "us"}. We're here to help with course enquiries, bookings, and any questions.`
              : "Get in touch with our team. We're here to help with course enquiries, bookings, and any questions you may have."}
          </p>
        </div>

        <div className="container mx-auto px-4">
          <div className="grid lg:grid-cols-3 gap-8">
            {/* Contact Info */}
            <div className="space-y-6">
              {contactInfo.map((info) => (
                <div key={info.title} className="bg-card border border-border rounded-xl p-5 flex items-start gap-4">
                  <div className="w-10 h-10 rounded-lg bg-primary/10 flex items-center justify-center shrink-0">
                    <info.icon className="w-5 h-5 text-primary" />
                  </div>
                  <div>
                    <div className="font-semibold text-foreground text-sm mb-1">{info.title}</div>
                    {info.lines.map((line) => (
                      <div key={line} className="text-sm text-muted-foreground">
                        {info.title === "Phone" ? (
                          <a href={`tel:${line.replace(/\s+/g, "")}`} className="hover:text-primary transition-colors">{line}</a>
                        ) : info.title === "Email" ? (
                          <a href={`mailto:${line}`} className="hover:text-primary transition-colors">{line}</a>
                        ) : (
                          line
                        )}
                      </div>
                    ))}
                  </div>
                </div>
              ))}
              {isTenantMode && contactInfo.length === 0 && (
                <p className="text-sm text-muted-foreground">Contact details not yet configured.</p>
              )}
            </div>

            {/* Contact Form */}
            <div className="lg:col-span-2">
              <form onSubmit={handleSubmit} className="bg-card border border-border rounded-xl p-6 md:p-8 space-y-5">
                <h2 className="text-xl font-bold text-foreground mb-2">Send us a message</h2>
                <div className="grid sm:grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-foreground mb-1.5">Full Name</label>
                    <input
                      type="text"
                      required
                      value={formData.name}
                      onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                      className="w-full px-4 py-2.5 rounded-lg bg-secondary border border-border text-foreground text-sm placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary"
                      placeholder="John Smith"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-foreground mb-1.5">Email Address</label>
                    <input
                      type="email"
                      required
                      value={formData.email}
                      onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                      className="w-full px-4 py-2.5 rounded-lg bg-secondary border border-border text-foreground text-sm placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary"
                      placeholder="john@example.com"
                    />
                  </div>
                </div>
                <div className="grid sm:grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-foreground mb-1.5">Phone Number</label>
                    <input
                      type="tel"
                      value={formData.phone}
                      onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
                      className="w-full px-4 py-2.5 rounded-lg bg-secondary border border-border text-foreground text-sm placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary"
                      placeholder="+44 123 456 789"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-foreground mb-1.5">Subject</label>
                    <input
                      type="text"
                      required
                      value={formData.subject}
                      onChange={(e) => setFormData({ ...formData, subject: e.target.value })}
                      className="w-full px-4 py-2.5 rounded-lg bg-secondary border border-border text-foreground text-sm placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary"
                      placeholder="Course Enquiry"
                    />
                  </div>
                </div>
                <div>
                  <label className="block text-sm font-medium text-foreground mb-1.5">Message</label>
                  <textarea
                    required
                    rows={5}
                    value={formData.message}
                    onChange={(e) => setFormData({ ...formData, message: e.target.value })}
                    className="w-full px-4 py-2.5 rounded-lg bg-secondary border border-border text-foreground text-sm placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary resize-none"
                    placeholder="How can we help you?"
                  />
                </div>
                <Button variant="hero" size="lg" type="submit" className="w-full sm:w-auto" disabled={sending}>
                  {sending ? "Sending..." : "Send Message"} <Send className="w-4 h-4 ml-1" />
                </Button>
              </form>
            </div>
          </div>
        </div>
      </div>
      <Footer />
    </div>
  );
};

export default ContactPage;
