"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { useTranslations } from "next-intl";
import type { OrgBilling } from "@/types";
import { Card } from "@/components/ui/card";

interface Props {
  /** Existing billing record, or null on first edit. */
  initial: OrgBilling | null;
  /**
   * True if the caller is on a personal org. Personal customers
   * (B2C — private individuals) don't have a company name or VAT
   * number; the form re-labels the company-name field as "Full name"
   * and hides VAT.
   */
  isPersonal: boolean;
  /** Default company name for company orgs on first edit. */
  orgName: string;
  /** Default full-name for personal orgs on first edit. */
  userName: string;
  /**
   * Default billing email — the address the user registered with.
   * Used on first edit (when `initial` is null). Customers can still
   * type a different address (e.g. accounting@…) but the registration
   * email is a sensible starting point.
   */
  userEmail: string;
}

/**
 * Editable billing form. Used by /settings/billing; the wizard's
 * inline billing step (Bug 35 phase 2) reuses the same shape but is
 * implemented separately because of its different submit semantics
 * (one combined wizard submit, vs. this page's standalone PUT).
 *
 * The form does NOT do client-side VAT format validation — too many
 * country variations to get right, and the API will reject empty
 * VAT for company orgs anyway. The asterisk on the field plus the
 * server error suffices.
 */
export function BillingSettingsForm({
  initial,
  isPersonal,
  orgName,
  userName,
  userEmail,
}: Props) {
  const t = useTranslations("settingsBilling");
  const tCommon = useTranslations("common");
  const router = useRouter();

  const [companyName, setCompanyName] = useState(
    initial?.companyName ?? (isPersonal ? userName : orgName)
  );
  const [streetAddress, setStreetAddress] = useState(
    initial?.streetAddress ?? ""
  );
  const [postalCode, setPostalCode] = useState(initial?.postalCode ?? "");
  const [city, setCity] = useState(initial?.city ?? "");
  const [country, setCountry] = useState(initial?.country ?? "CH");
  const [vatNumber, setVatNumber] = useState(initial?.vatNumber ?? "");
  // Default billing email to the user's registration email when no
  // record exists yet. They can change it (a separate accounting
  // address is common); we just want sensible pre-fill on first edit.
  const [billingEmail, setBillingEmail] = useState(
    initial?.billingEmail ?? userEmail ?? ""
  );
  const [notes, setNotes] = useState(initial?.notes ?? "");

  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState(false);

  const onSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitting(true);
    setError("");
    setSuccess(false);
    try {
      const res = await fetch("/api/billing", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          companyName,
          streetAddress,
          postalCode,
          city,
          country,
          vatNumber: vatNumber.trim() || null,
          billingEmail,
          notes: notes.trim() || null,
        }),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data.error || t("saveFailed"));
      }
      setSuccess(true);
      // Refresh server props so the form re-renders with the saved
      // record's timestamps. Subtle but useful: the "last updated"
      // line below ticks forward.
      router.refresh();
    } catch (e: any) {
      setError(e.message);
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <Card className="animate-in animate-in-delay-1">
      <form onSubmit={onSubmit} className="space-y-4">
        {/* Bug 35: this field stores `company_name` in the DB but
            the label changes by customer type:
              - Company (B2B): "Company name" — the legal entity.
              - Personal (B2C): "Full name" — the individual's
                invoice name (may differ from their session display
                name; e.g. legal name vs friendly name).
            Required for both. The DB column is NOT NULL either way. */}
        <div>
          <label className="block text-xs uppercase tracking-wider text-text-muted mb-1">
            {isPersonal ? t("fullName") : t("companyName")}{" "}
            <span className="text-red-400">*</span>
          </label>
          <input
            type="text"
            required
            value={companyName}
            onChange={(e) => setCompanyName(e.target.value)}
            className="w-full px-3 py-2 rounded-lg border border-border bg-surface-2 text-text-primary text-sm focus:outline-none focus:border-text-secondary"
          />
        </div>

        <div>
          <label className="block text-xs uppercase tracking-wider text-text-muted mb-1">
            {t("streetAddress")} <span className="text-red-400">*</span>
          </label>
          <input
            type="text"
            required
            value={streetAddress}
            onChange={(e) => setStreetAddress(e.target.value)}
            className="w-full px-3 py-2 rounded-lg border border-border bg-surface-2 text-text-primary text-sm focus:outline-none focus:border-text-secondary"
          />
        </div>

        <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
          <div>
            <label className="block text-xs uppercase tracking-wider text-text-muted mb-1">
              {t("postalCode")} <span className="text-red-400">*</span>
            </label>
            <input
              type="text"
              required
              value={postalCode}
              onChange={(e) => setPostalCode(e.target.value)}
              className="w-full px-3 py-2 rounded-lg border border-border bg-surface-2 text-text-primary text-sm focus:outline-none focus:border-text-secondary"
            />
          </div>
          <div className="sm:col-span-2">
            <label className="block text-xs uppercase tracking-wider text-text-muted mb-1">
              {t("city")} <span className="text-red-400">*</span>
            </label>
            <input
              type="text"
              required
              value={city}
              onChange={(e) => setCity(e.target.value)}
              className="w-full px-3 py-2 rounded-lg border border-border bg-surface-2 text-text-primary text-sm focus:outline-none focus:border-text-secondary"
            />
          </div>
        </div>

        <div>
          <label className="block text-xs uppercase tracking-wider text-text-muted mb-1">
            {t("country")} <span className="text-red-400">*</span>
          </label>
          <select
            required
            value={country}
            onChange={(e) => setCountry(e.target.value)}
            className="w-full px-3 py-2 rounded-lg border border-border bg-surface-2 text-text-primary text-sm focus:outline-none focus:border-text-secondary"
          >
            <option value="CH">Switzerland</option>
            <option value="LI">Liechtenstein</option>
            <option value="DE">Germany</option>
            <option value="AT">Austria</option>
            <option value="FR">France</option>
            <option value="IT">Italy</option>
          </select>
        </div>

        {/* Bug 35: VAT visible only for company customers (B2B).
            Personal customers (B2C — private individuals) don't have
            a VAT number; the API likewise doesn't require one for
            them. */}
        {!isPersonal && (
          <div>
            <label className="block text-xs uppercase tracking-wider text-text-muted mb-1">
              {t("vatNumber")} <span className="text-red-400">*</span>
            </label>
            <input
              type="text"
              required
              value={vatNumber}
              onChange={(e) => setVatNumber(e.target.value)}
              placeholder="CHE-123.456.789 MWST"
              className="w-full px-3 py-2 rounded-lg border border-border bg-surface-2 text-text-primary text-sm focus:outline-none focus:border-text-secondary"
            />
            <p className="text-xs text-text-muted mt-1">{t("vatHelp")}</p>
          </div>
        )}

        <div>
          <label className="block text-xs uppercase tracking-wider text-text-muted mb-1">
            {t("billingEmail")} <span className="text-red-400">*</span>
          </label>
          <input
            type="email"
            required
            value={billingEmail}
            onChange={(e) => setBillingEmail(e.target.value)}
            placeholder="invoices@example.com"
            className="w-full px-3 py-2 rounded-lg border border-border bg-surface-2 text-text-primary text-sm focus:outline-none focus:border-text-secondary"
          />
          <p className="text-xs text-text-muted mt-1">{t("billingEmailHelp")}</p>
        </div>

        <div>
          <label className="block text-xs uppercase tracking-wider text-text-muted mb-1">
            {t("notes")}{" "}
            <span className="text-text-muted normal-case">
              ({tCommon("optional")})
            </span>
          </label>
          <textarea
            value={notes}
            onChange={(e) => setNotes(e.target.value)}
            rows={3}
            className="w-full px-3 py-2 rounded-lg border border-border bg-surface-2 text-text-primary text-sm focus:outline-none focus:border-text-secondary"
            placeholder={t(
              isPersonal ? "notesPlaceholderPersonal" : "notesPlaceholder"
            )}
          />
        </div>

        {error && (
          <div className="text-xs text-red-400 bg-red-400/10 border border-red-400/20 rounded-lg px-3 py-2">
            {error}
          </div>
        )}
        {success && !error && (
          <div className="text-xs text-success bg-success/10 border border-success/20 rounded-lg px-3 py-2">
            {t("saved")}
          </div>
        )}

        <div className="flex items-center justify-between gap-3">
          {initial?.updatedAt && (
            <div className="text-xs text-text-muted">
              {t("lastUpdated", {
                when: new Date(initial.updatedAt).toLocaleString(),
              })}
            </div>
          )}
          <button
            type="submit"
            disabled={submitting}
            className="ml-auto text-sm font-medium px-4 py-2 rounded-lg bg-accent text-white hover:bg-accent/90 transition-colors disabled:opacity-50"
          >
            {submitting ? tCommon("loading") : t("save")}
          </button>
        </div>
      </form>
    </Card>
  );
}
