"use client";

import { ArrowLeft, ArrowRight, Check, Eye, EyeOff, FileUp, Globe2, LockKeyhole, PiggyBank, ShieldCheck, UserRound, WalletCards } from "lucide-react";
import { FormEvent, useEffect, useRef, useState } from "react";
import { COUNTRIES, getIdentityRule, getTaxIdName } from "@/lib/countries";

type DepositAccount = "Checking" | "Savings" | "Offshore Account";
type Result = { accountNumber: string; userId: string; emailSent: boolean };

export default function AccountOpeningForm({ initialAccount, initialCurrency, onClose }: { initialAccount: DepositAccount; initialCurrency: string; onClose: () => void }) {
  const [step, setStep] = useState(1);
  const [accountType, setAccountType] = useState(initialAccount);
  const [currency, setCurrency] = useState(initialCurrency);
  const [showPassword, setShowPassword] = useState(false);
  const [citizenship, setCitizenship] = useState("");
  const [documentName, setDocumentName] = useState("");
  const [minimumDeposit, setMinimumDeposit] = useState("25.00");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [result, setResult] = useState<Result | null>(null);
  const formRef = useRef<HTMLFormElement>(null);
  const identityRule = getIdentityRule(citizenship);
  useEffect(() => { fetch("/api/public/settings").then((response) => response.json()).then((data) => setMinimumDeposit(String(data.minimumOpeningDeposit))).catch(() => undefined); }, []);

  function next() {
    const section = formRef.current?.querySelector<HTMLElement>(`[data-step="${step}"]`);
    const controls = Array.from(section?.querySelectorAll<HTMLInputElement | HTMLSelectElement>("input, select") ?? []);
    if (!controls.every((control) => control.reportValidity())) return;
    setError("");
    setStep((current) => Math.min(5, current + 1));
  }

  async function submit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setLoading(true);
    setError("");
    const formData = new FormData(event.currentTarget);
    const data = Object.fromEntries(formData.entries());
    const document = formData.get("identityDocument");
    if (!(document instanceof File) || !document.size) { setError("Upload your identity document."); setLoading(false); return; }
    if (document.size > 5 * 1024 * 1024 || !["application/pdf", "image/jpeg", "image/png"].includes(document.type)) { setError("Identity document must be a PDF, JPEG, or PNG file no larger than 5 MB."); setLoading(false); return; }
    const identityDocumentData = await new Promise<string>((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(String(reader.result)); reader.onerror = reject; reader.readAsDataURL(document); });
    delete data.identityDocument;
    const response = await fetch("/api/accounts", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ...data, identityDocumentName: document.name, identityDocumentType: document.type, identityDocumentData, accountType, currency: accountType === "Offshore Account" ? currency : "USD", acceptedTerms: data.acceptedTerms === "on", certificationAccepted: data.certificationAccepted === "on" }) });
    const payload = await response.json();
    if (response.ok) setResult(payload);
    else setError(payload.message ?? "Unable to complete enrollment.");
    setLoading(false);
  }

  if (result) return <div className="account-created"><div className="created-check"><Check /></div><span className="eyebrow">ENROLLMENT RECEIVED</span><h2>Your account is pending verification.</h2><p>We generated your account details. Identity review and the minimum opening deposit of {minimumDeposit} must be completed before full activation.</p><div className="account-receipt"><div><small>ACCOUNT NUMBER</small><b>{result.accountNumber}</b></div><div><small>USER ID</small><b>{result.userId}</b></div><div><small>STATUS</small><b>Pending verification</b></div></div><div className="opening-deposit final-funding-notice"><p><b>Contact the bank to fund and activate</b><span>Contact TRUST WORLD BANK through the official support channel for instructions to make the minimum initial deposit of {minimumDeposit}. Your account remains pending and cannot become fully functional until the deposit is received, posted, and KYC is approved.</span></p></div><div className="credential-warning"><ShieldCheck /><p><b>Your password and PIN remain private.</b><span>They were securely hashed and cannot be emailed, retrieved, or viewed by staff. Keep the credentials you chose in a trusted password manager.</span></p></div><p className="email-result">{result.emailSent ? "A confirmation was sent to your email." : "Email delivery is not configured. Save the details shown above."}</p><button className="button navy full" onClick={onClose}>Return to TRUST WORLD BANK</button></div>;

  const accountOptions = [["Checking", WalletCards, "Everyday spending"], ["Savings", PiggyBank, "Save and earn interest"], ["Offshore Account", Globe2, "USD, GBP, EUR or CNY"]] as const;
  return <div className="opening-flow"><div className="opening-heading"><span className="eyebrow">SECURE ACCOUNT ENROLLMENT</span><h2>{["Choose your account", "Tell us about yourself", "Your address and profile", "Verify your identity", "Create secure access"][step - 1]}</h2><p>Step {step} of 5 · Information is encrypted in transit.</p></div><div className="step-track">{[1,2,3,4,5].map((item) => <span key={item} className={item <= step ? "active" : ""}>{item < step ? <Check /> : item}</span>)}</div><form ref={formRef} className="opening-form" onSubmit={submit}>
    <section data-step="1" hidden={step !== 1}><div className="deposit-options">{accountOptions.map(([name, Icon, description]) => <button key={name} type="button" className={accountType === name ? "selected" : ""} onClick={() => { setAccountType(name); if (name !== "Offshore Account") setCurrency("USD"); }}><span className="deposit-option-icon"><Icon /></span><span><b>{name}</b><small>{description}</small></span><span className="radio-dot" /></button>)}</div>{accountType === "Offshore Account" && <div className="currency-panel"><label>Primary account currency</label><div className="currency-grid">{[["USD","US Dollar","$"],["GBP","British Pound","£"],["EUR","Euro","€"],["CNY","Chinese Yuan","¥"]].map(([code,name,symbol]) => <button type="button" key={code} className={currency === code ? "selected" : ""} onClick={() => setCurrency(code)}><b>{symbol} {code}</b><small>{name}</small></button>)}</div></div>}<div className="info-callout"><ShieldCheck /><p><b>Application and verification</b><span>Opening an account is subject to identity, sanctions, fraud, and eligibility review. Submission does not guarantee activation.</span></p></div></section>
    <section data-step="2" hidden={step !== 2}><div className="form-grid three"><label>Legal first name<input name="firstName" autoComplete="given-name" required /></label><label>Middle name <small>(optional)</small><input name="middleName" autoComplete="additional-name" /></label><label>Legal last name<input name="lastName" autoComplete="family-name" required /></label></div><div className="form-grid two"><label>Date of birth<input name="dateOfBirth" type="date" required max={new Date(new Date().setFullYear(new Date().getFullYear()-18)).toISOString().slice(0,10)} /></label><label>Citizenship<select name="citizenship" required value={citizenship} onChange={(event) => setCitizenship(event.target.value)}><option value="" disabled>Select citizenship</option>{COUNTRIES.map((country) => <option key={country} value={country}>{country}</option>)}</select></label><label>Email address<input name="email" type="email" autoComplete="email" required /></label><label>Mobile phone<input name="phone" type="tel" autoComplete="tel" placeholder="+1 555 555 0100" required /></label></div></section>
    <section data-step="3" hidden={step !== 3}><div className="form-grid two"><label className="wide">Residential address<input name="addressLine1" autoComplete="address-line1" required /></label><label className="wide">Unit or suite <small>(optional)</small><input name="addressLine2" autoComplete="address-line2" /></label><label>City<input name="city" autoComplete="address-level2" required /></label><label>State / Province<input name="stateProvince" autoComplete="address-level1" required /></label><label>Postal code <small>(optional)</small><input name="postalCode" autoComplete="postal-code" /></label><label>Country<select name="country" autoComplete="country-name" required defaultValue=""><option value="" disabled>Select country</option>{COUNTRIES.map((country) => <option key={country} value={country}>{country}</option>)}</select></label><label>Occupation<input name="occupation" required /></label><label>Employer <small>(optional)</small><input name="employer" /></label><label>Primary source of funds<select name="sourceOfFunds" required defaultValue=""><option value="" disabled>Select source</option><option>Employment income</option><option>Business income</option><option>Investments</option><option>Retirement income</option><option>Inheritance</option><option>Grant</option><option>Other</option></select></label><label>Expected account activity<select name="expectedActivity" required defaultValue=""><option value="" disabled>Select activity</option><option>Everyday personal banking</option><option>Savings and investment</option><option>International transfers</option><option>Business-related payments</option></select></label><label>Beneficiary name <small>(optional)</small><input name="beneficiaryName" /></label><label>Beneficiary relationship <small>(optional)</small><input name="beneficiaryRelationship" placeholder="Spouse, child, parent…" /></label></div></section>
    <section data-step="4" hidden={step !== 4}><div className="identity-intro"><UserRound /><div><b>Customer Identification Program</b><p>Requirements are based on your selected citizenship. {citizenship ? identityRule.label : "Select your citizenship in step 2 to set identity-number limits."}</p></div></div><div className="form-grid two"><label>{getTaxIdName(citizenship)}<input name="taxId" inputMode="text" autoComplete="off" required minLength={4} maxLength={identityRule.taxIdMax} /><small>Maximum {identityRule.taxIdMax} letters or digits for {citizenship || "your country"}.</small></label><label>Government ID type<select name="governmentIdType" required defaultValue=""><option value="" disabled>Select ID</option><option>Driver license</option><option>Passport</option><option>National identity card</option><option>Residence permit</option></select></label><label className="wide">Government ID number<input name="governmentIdNumber" autoComplete="off" required minLength={4} maxLength={identityRule.governmentIdMax} /><small>Maximum {identityRule.governmentIdMax} letters or digits.</small></label></div><label className="document-upload"><input name="identityDocument" type="file" accept=".pdf,.jpg,.jpeg,.png,application/pdf,image/jpeg,image/png" required onChange={(event) => setDocumentName(event.target.files?.[0]?.name ?? "")} /><span className="upload-icon"><FileUp /></span><span><b>{documentName || "Upload identity document"}</b><small>Passport, national ID, residence permit, or driver license · PDF, JPEG or PNG · Maximum 5 MB</small></span><span className="upload-action">Choose file</span></label><div className="info-callout"><LockKeyhole /><p><b>Protected document storage</b><span>Your file is stored with the protected application record for authorized identity review. Additional proof of address or source-of-funds evidence may be requested.</span></p></div></section>
    <section data-step="5" hidden={step !== 5}><div className="form-grid one"><label>Choose a user ID<input name="userId" autoComplete="username" required minLength={6} pattern="[a-zA-Z0-9._-]{6,40}" /><small>6–40 letters, numbers, dots, underscores, or hyphens.</small></label><label>Create a password<div className="secret-field"><input name="password" type={showPassword ? "text" : "password"} autoComplete="new-password" required minLength={6} maxLength={12} pattern="(?=.*[A-Za-z])(?=.*[0-9]).{6,12}" /><button type="button" onClick={() => setShowPassword(!showPassword)} aria-label="Show or hide password">{showPassword ? <EyeOff /> : <Eye />}</button></div><small>6–12 characters with at least one letter and one number.</small></label><label>Choose a 6-digit security PIN<input name="pin" type="password" inputMode="numeric" autoComplete="off" pattern="[0-9]{6}" required maxLength={6} /><small>Used to confirm sensitive requests. Never share it with anyone.</small></label></div><div className="opening-deposit final-funding-notice"><p><b>Funding notice after submission</b><span>After you submit this application, contact TRUST WORLD BANK for approved instructions to make the minimum initial deposit of {minimumDeposit} {accountType === "Offshore Account" ? currency : "USD"}. Do not send funds to anyone claiming to be bank staff through unofficial channels. The account cannot be activated until the bank receives and posts the deposit.</span></p></div><div className="agreements"><label><input name="acceptedTerms" type="checkbox" required /><span>I consent to electronic records and agree to the account agreement, privacy notice, fee schedule, and funds-availability disclosure.</span></label><label><input name="certificationAccepted" type="checkbox" required /><span>I certify under penalty of perjury that the information provided is complete and accurate and that I am opening this account for myself.</span></label></div><div className="credential-warning"><ShieldCheck /><p><b>We will never email your password or PIN.</b><span>TRUST WORLD BANK employees cannot see these credentials. Store them securely.</span></p></div></section>
    {error && <p className="opening-error">{error}</p>}<div className="opening-actions">{step > 1 && <button type="button" className="back-button" onClick={() => { setError(""); setStep(step-1); }}><ArrowLeft /> Back</button>}<button type={step === 5 ? "submit" : "button"} className="button coral" onClick={step === 5 ? undefined : next} disabled={loading}>{loading ? "Creating secure record…" : step === 5 ? "Submit for verification" : "Continue"} <ArrowRight /></button></div>
  </form></div>;
}
