"use client";

import { useState } from "react";
import { Button, Dialog, Field, Input, Select } from "@/components/ui/kit";
import { useToast } from "@/components/ui/toast";
import { api, ApiError } from "@/lib/api";
import { formatPaise } from "@/lib/format";
import type { CustomerRow, Plan } from "@/lib/types";

/**
 * Creates a customer (admin or reseller portal) or a reseller (admin) with its first owner login.
 * The owner signs in with the email and password given here and can change the password later.
 */
export function TenantDialog({
  kind,
  endpoint,
  plans,
  resellers,
  onClose,
  onCreated,
}: {
  kind: "customer" | "reseller";
  endpoint: string;
  plans: Plan[];
  resellers?: { id: number; name: string }[];
  onClose: () => void;
  onCreated: (c: CustomerRow) => void;
}) {
  const toast = useToast();
  const [f, setF] = useState({ name: "", owner_name: "", owner_email: "", owner_password: "", plan_id: plans.find((p) => p.is_default)?.id ?? plans[0]?.id ?? "", reseller_id: "", commission: "10", markup: "30" });
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [busy, setBusy] = useState(false);
  const set = (k: keyof typeof f) => (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => setF({ ...f, [k]: e.target.value });

  async function save() {
    setBusy(true);
    setErrors({});
    const body: Record<string, unknown> = { name: f.name, owner_name: f.owner_name, owner_email: f.owner_email, owner_password: f.owner_password };
    if (endpoint.startsWith("/admin")) body.type = kind;
    if (kind === "customer") {
      body.plan_id = f.plan_id ? Number(f.plan_id) : null;
      if (resellers && f.reseller_id) body.reseller_id = Number(f.reseller_id);
    } else {
      body.commission_rate_bp = Math.round(Number(f.commission) * 100);
      body.max_markup_bp = Math.round(Number(f.markup) * 100);
    }
    try {
      const r = await api.post<{ data: CustomerRow }>(endpoint, body);
      onCreated(r.data);
    } catch (e) {
      if (e instanceof ApiError && Object.keys(e.fields).length) setErrors(e.fields);
      else toast("error", (e as Error).message);
    } finally {
      setBusy(false);
    }
  }

  return (
    <Dialog
      open
      onClose={onClose}
      title={kind === "customer" ? "New customer" : "New reseller"}
      description={kind === "customer" ? "Creates the workspace and its owner login. Share the sign-in details with the owner securely." : "Creates the reseller organisation and its owner login."}
      footer={
        <>
          <Button onClick={onClose}>Cancel</Button>
          <Button variant="primary" loading={busy} onClick={save}>
            Create {kind}
          </Button>
        </>
      }
    >
      <div className="grid gap-4 sm:grid-cols-2">
        <div className="sm:col-span-2">
          <Field label="Business name" htmlFor="td-name" error={errors.name}>
            <Input id="td-name" value={f.name} onChange={set("name")} invalid={!!errors.name} autoFocus />
          </Field>
        </div>
        <Field label="Owner's name" htmlFor="td-owner" error={errors.owner_name}>
          <Input id="td-owner" value={f.owner_name} onChange={set("owner_name")} invalid={!!errors.owner_name} />
        </Field>
        <Field label="Owner's email" htmlFor="td-email" error={errors.owner_email}>
          <Input id="td-email" type="email" value={f.owner_email} onChange={set("owner_email")} invalid={!!errors.owner_email} />
        </Field>
        <div className="sm:col-span-2">
          <Field label="Temporary password" htmlFor="td-pw" error={errors.owner_password} hint="At least 10 characters with a letter and a number.">
            <Input id="td-pw" type="text" autoComplete="new-password" value={f.owner_password} onChange={set("owner_password")} invalid={!!errors.owner_password} />
          </Field>
        </div>
        {kind === "customer" ? (
          <>
            <Field label="Plan" htmlFor="td-plan" error={errors.plan_id}>
              <Select id="td-plan" value={f.plan_id} onChange={set("plan_id")}>
                {resellers && <option value="">No plan (not billed)</option>}
                {plans.map((p) => (
                  <option key={p.id} value={p.id}>
                    {p.name}, {formatPaise(p.price_paise, { compact: true })}/{p.interval}
                    {p.trial_days ? ` (${p.trial_days}-day trial)` : ""}
                  </option>
                ))}
              </Select>
            </Field>
            {resellers && (
              <Field label="Reseller" htmlFor="td-reseller" error={errors.reseller_id}>
                <Select id="td-reseller" value={f.reseller_id} onChange={set("reseller_id")}>
                  <option value="">Direct customer</option>
                  {resellers.map((r) => (
                    <option key={r.id} value={r.id}>
                      {r.name}
                    </option>
                  ))}
                </Select>
              </Field>
            )}
          </>
        ) : (
          <>
            <Field label="Commission (%)" htmlFor="td-com" error={errors.commission_rate_bp} hint="Of each customer payment, before GST">
              <Input id="td-com" inputMode="decimal" value={f.commission} onChange={set("commission")} />
            </Field>
            <Field label="Max plan markup (%)" htmlFor="td-markup" error={errors.max_markup_bp} hint="How far above list price they may sell">
              <Input id="td-markup" inputMode="decimal" value={f.markup} onChange={set("markup")} />
            </Field>
          </>
        )}
      </div>
    </Dialog>
  );
}
