"use client";

import { useState } from "react";
import { FormSection } from "@/components/FormSection";

type FormFeedback = { type: "success" | "error"; text: string } | null;

const messageClassName = {
  success: "rounded border border-[#0F766E]/25 bg-emerald-50 p-4 text-sm font-bold text-[#0F766E]",
  error: "rounded border border-[#B91C1C]/25 bg-red-50 p-4 text-sm font-bold text-[#B91C1C]"
};

export function IraTrustForm() {
  const [message, setMessage] = useState<FormFeedback>(null);
  const [submitting, setSubmitting] = useState(false);
  async function submit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    if (submitting) return;
    const formElement = event.currentTarget;
    setSubmitting(true);
    setMessage(null);
    try {
      const form = new FormData(formElement);
      const res = await fetch("/api/ira-trust", { method: "POST", body: form });
      if (!res.ok) {
        setMessage({ type: "error", text: "Please review the required fields and try again." });
        return;
      }
      setMessage({ type: "success", text: "Application received. Authorized staff will review the request and follow up with next steps." });
      formElement.reset();
    } catch {
      setMessage({ type: "error", text: "We could not submit the application. Please try again." });
    } finally {
      setSubmitting(false);
    }
  }
  return (
    <form onSubmit={submit} className="grid gap-5">
      <input type="text" name="companyUrl" tabIndex={-1} autoComplete="off" aria-hidden="true" className="hidden" />
      <FormSection title="Personal Information">
        <label>Full Name<input name="fullName" required /></label>
        <label>Email<input name="email" type="email" required /></label>
        <label>Phone<input name="phone" required /></label>
        <label>Date of Birth<input name="dateOfBirth" type="date" required /></label>
        <label>Citizenship Status<input name="citizenshipStatus" required /></label>
        <label>SSN optional<span className="text-xs text-[#666]">Used only if required for additional account review.</span><input name="ssnOptional" /></label>
        <label className="md:col-span-2">Address<textarea name="address" required /></label>
        <p className="text-sm leading-6 text-[#666] md:col-span-2">Only provide sensitive information when necessary for this request. Submitted details are reviewed by authorized staff through the admin panel.</p>
      </FormSection>
      <FormSection title="Account Preferences">
        <label>Account Type<select name="accountType"><option>Traditional IRA</option><option>Roth IRA</option><option>SEP IRA</option><option>401(k) Rollover</option><option>Trust Gold/Silver Account</option></select></label>
        <label>Investment Preference<select name="investmentPreference"><option>Gold</option><option>Silver</option><option>Both</option></select></label>
        <label>Storage Preference<select name="storagePreference"><option>Allocated Storage</option><option>Segregated Storage</option><option>Custodian-Approved Vault</option></select></label>
        <label>Affiliate Custodian Partner<select name="custodianPartner"><option>Equity Trust</option><option>Strata Trust</option><option>Preferred Trust</option><option>GoldStar Trust</option></select></label>
      </FormSection>
      <FormSection title="Agreements">
        {[
          ["amlKycAccepted", "AML/KYC"],
          ["custodianAgreementAccepted", "Custodian Agreement"],
          ["storageAgreementAccepted", "Storage Agreement"],
          ["serviceAgreementAccepted", "Service Agreement"]
        ].map(([name, label]) => <label key={name} className="flex-row items-center gap-2"><input className="h-4 min-h-0 w-4" type="checkbox" name={name} required /> {label}</label>)}
      </FormSection>
      {message ? <div aria-live="polite" className={messageClassName[message.type]}>{message.text}</div> : null}
      <button className="btn btn-primary w-full disabled:cursor-not-allowed disabled:opacity-60 sm:w-fit" disabled={submitting}>
        {submitting ? "Submitting..." : "Submit Application"}
      </button>
    </form>
  );
}

export function SellBackForm() {
  const [message, setMessage] = useState<FormFeedback>(null);
  const [submitting, setSubmitting] = useState(false);
  async function submit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    if (submitting) return;
    const formElement = event.currentTarget;
    setSubmitting(true);
    setMessage(null);
    try {
      const form = new FormData(formElement);
      const res = await fetch("/api/sell-back", { method: "POST", body: form });
      if (!res.ok) {
        setMessage({ type: "error", text: "Please complete the required sell-back details and try again." });
        return;
      }
      setMessage({ type: "success", text: "Sell-back request received. Our team will manually review the details and follow up with next steps." });
      formElement.reset();
    } catch {
      setMessage({ type: "error", text: "We could not submit the sell-back request. Please try again." });
    } finally {
      setSubmitting(false);
    }
  }
  return (
    <form onSubmit={submit} className="grid gap-5">
      <input type="text" name="companyUrl" tabIndex={-1} autoComplete="off" aria-hidden="true" className="hidden" />
      <FormSection title="Owner & Product Details">
        <label>Full Name<input name="fullName" required /></label>
        <label>Email<input name="email" type="email" required /></label>
        <label>Phone<input name="phone" required /></label>
        <label>Product Type<input name="productType" required /></label>
        <label>Weight<input name="weight" required /></label>
        <label>Mint/Brand<input name="mintBrand" required /></label>
        <label>Serial Number for Bars<input name="serialNumber" /></label>
        <label>Purchase Date<input name="purchaseDate" type="date" /></label>
        <label>Purchase Source<input name="purchaseSource" /></label>
        <label>Condition<input name="condition" required /></label>
        <label>Packaging Condition<input name="packagingCondition" required /></label>
        <label>Photo Links<span className="text-xs text-[#666]">Add JPG, PNG, or PDF links when available.</span><input name="photoUrls" /></label>
      </FormSection>
      <FormSection title="Declarations">
        <label className="md:col-span-2">Bank Details for Payout<textarea name="bankDetailsForPayout" required /></label>
        <label>Signature<input name="signature" required /></label>
        <label className="flex-row items-center gap-2"><input className="h-4 min-h-0 w-4" type="checkbox" name="ownershipDeclarationAccepted" required /> Ownership Declaration</label>
        <label className="flex-row items-center gap-2"><input className="h-4 min-h-0 w-4" type="checkbox" name="amlKycAccepted" required /> AML/KYC Confirmation</label>
        <p className="text-sm leading-6 text-[#666] md:col-span-2">Only provide sensitive information when necessary for this request. Submitted details are reviewed by authorized staff through the admin panel for request handling and payout coordination.</p>
      </FormSection>
      {message ? <div aria-live="polite" className={messageClassName[message.type]}>{message.text}</div> : null}
      <button className="btn btn-primary w-full disabled:cursor-not-allowed disabled:opacity-60 sm:w-fit" disabled={submitting}>
        {submitting ? "Submitting..." : "Submit Sell-Back Request"}
      </button>
    </form>
  );
}

export function ContactForm() {
  const [message, setMessage] = useState<FormFeedback>(null);
  const [submitting, setSubmitting] = useState(false);
  async function submit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    if (submitting) return;
    const formElement = event.currentTarget;
    setSubmitting(true);
    setMessage(null);
    try {
      const form = new FormData(formElement);
      const res = await fetch("/api/support", { method: "POST", body: form });
      if (!res.ok) {
        setMessage({ type: "error", text: "Please complete the required support fields and try again." });
        return;
      }
      setMessage({ type: "success", text: "Support ticket received. Our team will review your message and respond as soon as possible." });
      formElement.reset();
    } catch {
      setMessage({ type: "error", text: "We could not send your message. Please try again." });
    } finally {
      setSubmitting(false);
    }
  }
  return (
    <form onSubmit={submit} className="panel grid gap-4 p-5 md:grid-cols-2">
      <input type="text" name="companyUrl" tabIndex={-1} autoComplete="off" aria-hidden="true" className="hidden" />
      <label>Full Name<input name="fullName" required /></label>
      <label>Email<input name="email" type="email" required /></label>
      <label>Phone<input name="phone" /></label>
      <label>Subject<input name="subject" required /></label>
      <label className="md:col-span-2">Message<textarea name="message" required /></label>
      <label className="md:col-span-2">Attachment Link<input name="attachmentUrl" placeholder="JPG, PNG, PDF up to 10 MB" /></label>
      <p className="text-sm text-[#666] md:col-span-2">Attachments may be JPG, PNG, or PDF up to 10 MB. Submission limits may apply.</p>
      {message ? <div aria-live="polite" className={`md:col-span-2 ${messageClassName[message.type]}`}>{message.text}</div> : null}
      <button className="btn btn-primary w-full disabled:cursor-not-allowed disabled:opacity-60 sm:w-fit" disabled={submitting}>
        {submitting ? "Sending..." : "Send Message"}
      </button>
    </form>
  );
}
