"use client";

import { useState, type FormEvent } from "react";

import {
  ArrowRight,
  CheckCircle2,
} from "lucide-react";

type SubmissionResult = {
  success?: boolean;
  leadCode?: string;
  error?: string;
  retryAfterSeconds?: number;
  fields?: Record<string, string[] | undefined>;
};

export default function RequestQuotePage() {
  const [submitting, setSubmitting] = useState(false);
  const [successCode, setSuccessCode] = useState<string | null>(null);
  const [formError, setFormError] = useState<string | null>(null);

  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();

    if (submitting) return;

    const form = event.currentTarget;
    const values = new FormData(form);

    const payload = {
      name: String(values.get("name") ?? "").trim(),
      companyName: String(values.get("companyName") ?? "").trim(),
      email: String(values.get("email") ?? "").trim(),
      phone: String(values.get("phone") ?? "").trim(),
      service: String(values.get("service") ?? "").trim(),
      message: String(values.get("message") ?? "").trim(),
    };

    setSubmitting(true);
    setSuccessCode(null);
    setFormError(null);

    try {
      const response = await fetch("/api/leads", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "Accept": "application/json",
        },
        body: JSON.stringify(payload),
      });

      const result: SubmissionResult = await response.json();

      if (
        response.status === 201 &&
        result.success === true &&
        typeof result.leadCode === "string" &&
        /^TTL-[A-F0-9]{20}$/.test(result.leadCode)
      ) {
        setSuccessCode(result.leadCode);
        form.reset();
        return;
      }

      if (response.status === 429) {
        const minutes =
          typeof result.retryAfterSeconds === "number"
            ? Math.max(1, Math.ceil(result.retryAfterSeconds / 60))
            : 15;

        setFormError(
          `Too many submissions. Please try again in approximately ${minutes} minute(s).`,
        );
        return;
      }

      if (response.status === 400 && result.fields) {
        const firstFieldError = Object.values(result.fields)
          .flat()
          .find((message): message is string =>
            typeof message === "string",
          );

        setFormError(
          firstFieldError ??
            "Please check the information and try again.",
        );
        return;
      }

      setFormError(
        "We could not submit your requirement. Please try again.",
      );
    } catch {
      setFormError(
        "Connection error. Please check your internet connection and try again.",
      );
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <main>
      <section className="inner-hero">
        <div className="inner-hero-grid" />

        <div className="container inner-hero-content">
          <span className="section-label">
            REQUEST A QUOTE
          </span>

          <h1>Tell us what you want to build.</h1>

          <p>
            Share your requirement and project information.
            Our team can review the scope and discuss the
            appropriate technology approach.
          </p>
        </div>
      </section>

      <section className="section">
        <div className="container quote-layout">

          <div className="quote-info">
            <span className="section-label">
              PROJECT REQUIREMENT
            </span>

            <h2>
              Start with your business requirement.
            </h2>

            <p>
              You do not need to know the technical details.
              Explain the problem, workflow or product you
              want to create.
            </p>

            {[
              "Website or Web Application",
              "Mobile Application",
              "Custom Software",
              "ERP or CRM",
              "FinTech Integration",
              "API Integration",
            ].map((item) => (
              <div className="quote-check" key={item}>
                <CheckCircle2 size={18} />
                {item}
              </div>
            ))}
          </div>

          <form
            className="quote-form"
            onSubmit={handleSubmit}
          >
            <div className="form-grid">

              <label>
                Full Name
                <input
                  type="text"
                  name="name"
                  autoComplete="name"
                  minLength={2}
                  maxLength={150}
                  placeholder="Your name"
                  required
                />
              </label>

              <label>
                Company
                <input
                  type="text"
                  name="companyName"
                  autoComplete="organization"
                  maxLength={191}
                  placeholder="Company name"
                />
              </label>

              <label>
                Email
                <input
                  type="email"
                  name="email"
                  autoComplete="email"
                  maxLength={191}
                  placeholder="name@company.com"
                  required
                />
              </label>

              <label>
                Phone
                <input
                  type="tel"
                  name="phone"
                  autoComplete="tel"
                  minLength={7}
                  maxLength={30}
                  placeholder="+91"
                  required
                />
              </label>

              <label className="full-field">
                Project Type
                <select name="service" defaultValue="" required>
                  <option value="" disabled>
                    Select project type
                  </option>
                  <option>Website / Web Application</option>
                  <option>Mobile Application</option>
                  <option>Custom Software</option>
                  <option>ERP / CRM</option>
                  <option>FinTech Integration</option>
                  <option>API Integration</option>
                  <option>Other</option>
                </select>
              </label>

              <label className="full-field">
                Requirement
                <textarea
                  name="message"
                  rows={7}
                  minLength={10}
                  maxLength={5000}
                  placeholder="Describe your project, workflow or requirement..."
                  required
                />
              </label>

            </div>

            <button
              type="submit"
              className="button quote-submit"
              disabled={submitting}
              aria-busy={submitting}
            >
              {submitting ? "Submitting..." : "Submit Requirement"}
              <ArrowRight size={18} />
            </button>

            {successCode && (
              <div role="status" aria-live="polite" className="form-note">
                <strong>Requirement submitted successfully.</strong>
                <br />
                Your Lead Reference Number: <strong>{successCode}</strong>
                <br />
                Please save this reference for future communication.
              </div>
            )}

            {formError && (
              <div role="alert" className="form-note">
                {formError}
              </div>
            )}

            <small className="form-note">
              Our team will review your requirement and contact you
              using the details provided.
            </small>
          </form>

        </div>
      </section>
    </main>
  );
}
