"use client"

import { useState } from "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 { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Mail, ShieldCheck } from "lucide-react"
import { fetchApi } from "@/lib/api-client"
import { toast } from "sonner"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import * as z from "zod"

const contactSchema = z.object({
  name: z.string().min(2, "Name must be at least 2 characters"),
  email: z.string().email("Invalid email address"),
  subject: z.string().min(5, "Subject must be at least 5 characters"),
  message: z.string().min(10, "Message must be at least 10 characters"),
})

type ContactFormValues = z.infer<typeof contactSchema>

export default function ContactPage() {
  const [content, setContent] = useState<any>({})
  const [isSubmitting, setIsSubmitting] = useState(false)

  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm<ContactFormValues>({
    resolver: zodResolver(contactSchema),
    defaultValues: {
      name: "",
      email: "",
      subject: "",
      message: "",
    },
  })

  useState(() => {
    fetchApi('content.php?page=contact').then(setContent).catch(console.error)
  })

  async function onSubmit(values: ContactFormValues) {
    setIsSubmitting(true)
    try {
      await fetchApi('contact.php', {
        method: 'POST',
        body: JSON.stringify(values)
      })
      toast.success("Message sent successfully!")
      reset()
    } catch (error: any) {
      toast.error(error.message || "Failed to send message")
    } finally {
      setIsSubmitting(false)
    }
  }

  const faqs = [
    { q: content.faq?.q1, a: content.faq?.a1 },
    { q: content.faq?.q2, a: content.faq?.a2 },
  ].filter(f => f.q && f.a);

  return (
    <main className="flex-1">
      <section className="bg-primary/5 py-16 border-b">
        <div className="container mx-auto px-4">
          <h1 className="text-4xl font-bold mb-4">Contact OncoConnect</h1>
          <p className="text-xl text-muted-foreground max-w-2xl">
            Have questions about the platform, verification process, or interested in partnering with us? We&apos;re
            here to help.
          </p>
        </div>
      </section>

      <section className="container mx-auto px-4 py-12">
        <div className="grid lg:grid-cols-2 gap-12">
          <div className="space-y-8">
            <div className="grid sm:grid-cols-2 gap-6">
              <Card>
                <CardHeader className="pb-2">
                  <CardTitle className="text-sm font-bold flex items-center gap-2">
                    <Mail className="h-4 w-4 text-primary" />
                    Support Email
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <p className="text-sm text-muted-foreground">{content.support?.email || "support@oncoconnect.org"}</p>
                </CardContent>
              </Card>
              <Card>
                <CardHeader className="pb-2">
                  <CardTitle className="text-sm font-bold flex items-center gap-2">
                    <ShieldCheck className="h-4 w-4 text-secondary" />
                    Expert Verification
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <p className="text-sm text-muted-foreground">{content.verification?.email || "verify@oncoconnect.org"}</p>
                </CardContent>
              </Card>
            </div>

            <div className="space-y-4">
              <h2 className="text-2xl font-bold">Frequently Asked Questions</h2>
              <div className="space-y-4">
                {faqs.length > 0 ? faqs.map((faq, index) => (
                  <div key={index} className="p-4 rounded-xl border bg-muted/30">
                    <p className="font-bold text-sm mb-1">{faq.q}</p>
                    <p className="text-xs text-muted-foreground">{faq.a}</p>
                  </div>
                )) : (
                  <>
                    <div className="p-4 rounded-xl border bg-muted/30">
                      <p className="font-bold text-sm mb-1">How do I report misinformation?</p>
                      <p className="text-xs text-muted-foreground">
                        Use the flag icon on any post or comment. Our moderation team reviews all reports within 4 hours.
                      </p>
                    </div>
                    <div className="p-4 rounded-xl border bg-muted/30">
                      <p className="font-bold text-sm mb-1">Is my data shared with pharma companies?</p>
                      <p className="text-xs text-muted-foreground">
                        No. OncoConnect is a non-profit initiative and we never sell or share user data for commercial
                        purposes.
                      </p>
                    </div>
                  </>
                )}
              </div>
            </div>
          </div>

          <Card>
            <CardHeader>
              <CardTitle>Send us a message</CardTitle>
            </CardHeader>
            <CardContent>
              <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="name">Name</Label>
                    <Input
                      id="name"
                      placeholder="John Doe"
                      {...register("name")}
                    />
                    {errors.name && (
                      <p className="text-xs font-medium text-destructive">{errors.name.message}</p>
                    )}
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="email">Email</Label>
                    <Input
                      id="email"
                      placeholder="m@example.com"
                      type="email"
                      {...register("email")}
                    />
                    {errors.email && (
                      <p className="text-xs font-medium text-destructive">{errors.email.message}</p>
                    )}
                  </div>
                </div>
                <div className="space-y-2">
                  <Label htmlFor="subject">Subject</Label>
                  <Input
                    id="subject"
                    placeholder="What can we help you with?"
                    {...register("subject")}
                  />
                  {errors.subject && (
                    <p className="text-xs font-medium text-destructive">{errors.subject.message}</p>
                  )}
                </div>
                <div className="space-y-2">
                  <Label htmlFor="message">Message</Label>
                  <Textarea
                    id="message"
                    placeholder="Type your message here..."
                    className="min-h-[150px]"
                    {...register("message")}
                  />
                  {errors.message && (
                    <p className="text-xs font-medium text-destructive">{errors.message.message}</p>
                  )}
                </div>
                <Button type="submit" className="w-full font-bold shadow-lg" disabled={isSubmitting}>
                  {isSubmitting ? "Sending..." : "Send Message"}
                </Button>
              </form>
            </CardContent>
          </Card>
        </div>
      </section>
    </main>
  )
}
