"use client";

import { useCallback, useEffect, useState, type FormEvent } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { toast } from "sonner";
import { getApiErrorMessage } from "@/lib/api-error";
import { tenantPublicUrl } from "@/lib/org-slug";
import {
  fetchOrgSettings,
  updateOrgSettings,
  type OrgSettings,
} from "@/platform/api/org-settings-api";

export default function OrgBusinessSettings({ orgKey }: { orgKey: string }) {
  const [settings, setSettings] = useState<OrgSettings | null>(null);
  const [name, setName] = useState("");
  const [slug, setSlug] = useState("");
  const [unitLabel, setUnitLabel] = useState("Unit");
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);

  const load = useCallback(async () => {
    if (!orgKey) return;
    setLoading(true);
    try {
      const data = await fetchOrgSettings(orgKey);
      setSettings(data);
      setName(data.name || "");
      setSlug(data.slug || "");
      setUnitLabel(data.unitLabel || "Unit");
    } catch (e) {
      toast.error(getApiErrorMessage(e, "Failed to load business profile"));
    } finally {
      setLoading(false);
    }
  }, [orgKey]);

  useEffect(() => {
    load();
  }, [load]);

  const onSave = async (e: FormEvent) => {
    e.preventDefault();
    setSaving(true);
    try {
      const data = await updateOrgSettings(orgKey, { name, slug, unitLabel });
      setSettings(data);
      setName(data.name);
      setSlug(data.slug);
      setUnitLabel(data.unitLabel);
      toast.success("Business profile saved");
      if (typeof window !== "undefined" && data.slug && window.location.pathname.startsWith(`/${settings?.slug}/`)) {
        if (data.slug !== settings?.slug) {
          window.location.replace(`/${data.slug}/settings`);
        }
      }
    } catch (err) {
      toast.error(getApiErrorMessage(err, "Could not save business profile"));
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return <p className="rounded-md border bg-white p-8 text-center text-sm text-muted-foreground">Loading…</p>;
  }

  if (!settings) {
    return (
      <p className="rounded-md border bg-white p-6 text-sm text-slate-600">
        You do not have access to this business profile.
      </p>
    );
  }

  return (
    <form onSubmit={onSave} className="max-w-xl space-y-4 rounded-lg border bg-white p-6">
      <div className="space-y-1">
        <Label htmlFor="org-name">Business name</Label>
        <Input id="org-name" value={name} onChange={(e) => setName(e.target.value)} required />
      </div>
      <div className="space-y-1">
        <Label htmlFor="org-slug">Workspace URL slug</Label>
        <Input id="org-slug" value={slug} onChange={(e) => setSlug(e.target.value)} required />
        {slug ? (
          <p className="text-xs text-muted-foreground">{tenantPublicUrl(slug)}</p>
        ) : null}
      </div>
      <div className="space-y-1">
        <Label htmlFor="org-unit-label">Unit label</Label>
        <Input
          id="org-unit-label"
          value={unitLabel}
          onChange={(e) => setUnitLabel(e.target.value)}
          placeholder="Branch, Plant, Location…"
        />
        <p className="text-xs text-muted-foreground">
          Shown in the unit switcher (for example Plant vs Branch).
        </p>
      </div>
      <div className="rounded-md border bg-slate-50 p-3 text-sm">
        <p className="font-medium text-slate-800">Custom domain</p>
        <p className="mt-1 text-slate-600">
          {settings.customDomain
            ? `${settings.customDomain} · ${settings.domainStatus}`
            : "Not set. Ask a Nizamify admin to attach a domain."}
        </p>
      </div>
      <Button type="submit" disabled={saving}>
        {saving ? "Saving…" : "Save business profile"}
      </Button>
    </form>
  );
}
