"use client";

import { useEffect, useState } from "react";
import { useCurrentUser } from "@/lib/hooks/useCurrentUser";
import { apiFetch, ApiClientError } from "@/lib/api/client";
import { Card, CardHeader, CardBody } from "@/components/ui/Card";
import { Input } from "@/components/ui/Input";
import { Button } from "@/components/ui/Button";

interface OrganizationDetail {
  id: string;
  name: string;
  currency: string;
  timezone: string;
  country: string;
  address: string | null;
  city: string | null;
  state: string | null;
  phone: string | null;
  email: string | null;
  website: string | null;
}

export default function OrganizationSettingsPage() {
  const { currentOrg, loading: loadingUser } = useCurrentUser();
  const [org, setOrg] = useState<OrganizationDetail | null>(null);
  const [saving, setSaving] = useState(false);
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);

  useEffect(() => {
    if (!currentOrg) return;
    apiFetch<{ organization: OrganizationDetail }>(`/api/v1/organizations/${currentOrg.id}`).then((res) =>
      setOrg(res.organization)
    );
  }, [currentOrg]);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!org) return;
    setSaving(true);
    setMessage(null);
    try {
      const { organization } = await apiFetch<{ organization: OrganizationDetail }>(`/api/v1/organizations/${org.id}`, {
        method: "PATCH",
        body: JSON.stringify({
          name: org.name,
          address: org.address || undefined,
          city: org.city || undefined,
          state: org.state || undefined,
          phone: org.phone || undefined,
          email: org.email || undefined,
          website: org.website || undefined,
        }),
      });
      setOrg(organization);
      setMessage({ type: "success", text: "Organization updated." });
    } catch (err) {
      setMessage({ type: "error", text: err instanceof ApiClientError ? err.message : "Could not save changes." });
    } finally {
      setSaving(false);
    }
  }

  if (loadingUser || (!org && currentOrg)) {
    return <p className="text-sm text-ink-muted">Loading…</p>;
  }
  if (!currentOrg || !org) {
    return <p className="text-sm text-ink-muted">No organization found for your account.</p>;
  }

  return (
    <div className="max-w-2xl">
      <h1 className="mb-6 text-lg font-semibold text-ink">Organization settings</h1>
      <Card>
        <CardHeader title="Business details" description="Shown on receipts, vouchers, and the captive portal once configured." />
        <CardBody>
          <form onSubmit={handleSubmit} className="grid grid-cols-1 gap-4 sm:grid-cols-2">
            <div className="sm:col-span-2">
              <Input label="Organization name" value={org.name} onChange={(e) => setOrg({ ...org, name: e.target.value })} required />
            </div>
            <Input label="Address" value={org.address ?? ""} onChange={(e) => setOrg({ ...org, address: e.target.value })} />
            <Input label="City" value={org.city ?? ""} onChange={(e) => setOrg({ ...org, city: e.target.value })} />
            <Input label="State" value={org.state ?? ""} onChange={(e) => setOrg({ ...org, state: e.target.value })} />
            <Input label="Phone" value={org.phone ?? ""} onChange={(e) => setOrg({ ...org, phone: e.target.value })} />
            <Input label="Support email" type="email" value={org.email ?? ""} onChange={(e) => setOrg({ ...org, email: e.target.value })} />
            <Input label="Website" value={org.website ?? ""} onChange={(e) => setOrg({ ...org, website: e.target.value })} />

            {message && (
              <p className={`sm:col-span-2 text-sm ${message.type === "success" ? "text-status-online" : "text-status-offline"}`}>
                {message.text}
              </p>
            )}

            <div className="sm:col-span-2">
              <Button type="submit" disabled={saving}>
                {saving ? "Saving…" : "Save changes"}
              </Button>
            </div>
          </form>
        </CardBody>
      </Card>
    </div>
  );
}
