import { useState } from "react";
import { Send, CheckCircle2 } from "lucide-react";
import { z } from "zod";
import { SITE, WHATSAPP_LINK } from "@/lib/site";

const schema = z.object({
  name: z.string().trim().min(2, "Please enter your name").max(80),
  email: z.string().trim().email("Please enter a valid email").max(200),
  website: z.string().trim().max(200).optional().or(z.literal("")),
  issue: z.string().trim().min(10, "Please describe the issue (min 10 chars)").max(2000),
});

export function ContactForm() {
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [sent, setSent] = useState(false);

  const onSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const data = Object.fromEntries(new FormData(e.currentTarget));
    const result = schema.safeParse(data);
    if (!result.success) {
      const errs: Record<string, string> = {};
      result.error.issues.forEach((i) => {
        if (i.path[0]) errs[String(i.path[0])] = i.message;
      });
      setErrors(errs);
      return;
    }
    setErrors({});
    // Send via WhatsApp deep link as a no-backend fallback.
    const text = `Hi ${SITE.name}!%0A%0AName: ${encodeURIComponent(result.data.name)}%0AEmail: ${encodeURIComponent(result.data.email)}%0AWebsite: ${encodeURIComponent(result.data.website || "—")}%0A%0AIssue:%0A${encodeURIComponent(result.data.issue)}`;
    window.open(`https://wa.me/${SITE.whatsapp}?text=${text}`, "_blank", "noopener");
    setSent(true);
  };

  if (sent) {
    return (
      <div className="rounded-2xl border border-emerald/30 bg-emerald/5 p-8 text-center">
        <CheckCircle2 className="mx-auto h-12 w-12 text-emerald" />
        <h3 className="mt-4 text-xl font-display font-semibold">Message ready to send!</h3>
        <p className="mt-2 text-muted-foreground">We opened WhatsApp for you. Hit send and we'll reply within 30 minutes.</p>
        <a
          href={WHATSAPP_LINK}
          target="_blank"
          rel="noopener noreferrer"
          className="mt-6 inline-flex items-center justify-center rounded-lg bg-gradient-emerald px-5 py-2.5 font-semibold text-navy-deep"
        >
          Reopen WhatsApp
        </a>
      </div>
    );
  }

  return (
    <form onSubmit={onSubmit} className="rounded-2xl border border-border bg-card p-6 md:p-8 shadow-soft space-y-5">
      <Field name="name" label="Your name" placeholder="Jane Doe" error={errors.name} />
      <Field name="email" label="Email" type="email" placeholder="you@company.com" error={errors.email} />
      <Field name="website" label="Website URL (optional)" placeholder="https://example.com" error={errors.website} />
      <div>
        <label className="block text-sm font-medium mb-1.5" htmlFor="issue">Describe the issue</label>
        <textarea
          id="issue"
          name="issue"
          rows={5}
          maxLength={2000}
          placeholder="Tell us what's broken — error messages, when it started, etc."
          className="w-full rounded-lg border border-input bg-background px-3.5 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
        />
        {errors.issue && <p className="mt-1.5 text-xs text-destructive">{errors.issue}</p>}
      </div>
      <button
        type="submit"
        className="w-full inline-flex items-center justify-center gap-2 rounded-lg bg-gradient-emerald px-6 py-3.5 font-semibold text-navy-deep shadow-emerald hover:shadow-glow transition-shadow"
      >
        <Send className="h-4 w-4" /> Send Request — Reply in 30 mins
      </button>
      <p className="text-xs text-center text-muted-foreground">
        We'll never share your details. By submitting you agree to be contacted about your request.
      </p>
    </form>
  );
}

function Field({
  name,
  label,
  placeholder,
  type = "text",
  error,
}: {
  name: string;
  label: string;
  placeholder?: string;
  type?: string;
  error?: string;
}) {
  return (
    <div>
      <label className="block text-sm font-medium mb-1.5" htmlFor={name}>{label}</label>
      <input
        id={name}
        name={name}
        type={type}
        placeholder={placeholder}
        maxLength={200}
        className="w-full rounded-lg border border-input bg-background px-3.5 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
      />
      {error && <p className="mt-1.5 text-xs text-destructive">{error}</p>}
    </div>
  );
}
