"use client";

import { useState, type FormEvent } from "react";
import { Button, ConfirmDialog, Field, Input, PageHeader, Panel, Select, Skeleton } from "@/components/ui/kit";
import { useToast } from "@/components/ui/toast";
import { useSession } from "@/components/session";
import { api, ApiError } from "@/lib/api";
import { useApi } from "@/lib/use-api";

interface Workspace {
  id: number;
  name: string;
  timezone: string;
  message_retention_days: number | null;
  redacted_messages: number;
}
const RETENTION_LABEL: Record<string, string> = { "": "Keep message content", "30": "30 days", "90": "90 days", "180": "6 months", "365": "1 year", "730": "2 years" };

function zones() {
  try {
    const list = Intl.supportedValuesOf("timeZone");
    return list.includes("Asia/Kolkata") ? list : ["Asia/Kolkata", ...list];
  } catch {
    return ["Asia/Kolkata", "UTC"];
  }
}

function WorkspaceForm({ w, choices, onSaved }: { w: Workspace; choices: number[]; onSaved: () => void }) {
  const toast = useToast();
  const { refresh } = useSession();
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [busy, setBusy] = useState(false);
  const [pending, setPending] = useState<Record<string, unknown> | null>(null);

  async function save(body: Record<string, unknown>) {
    setBusy(true);
    setErrors({});
    try {
      await api.patch("/workspace", body);
      toast("success", "Workspace settings saved");
      setPending(null);
      onSaved();
      refresh();
    } catch (err) {
      if (err instanceof ApiError && Object.keys(err.fields).length) setErrors(err.fields);
      else toast("error", (err as Error).message);
    } finally {
      setBusy(false);
    }
  }

  function submit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const f = new FormData(e.currentTarget);
    const retention = String(f.get("retention") ?? "");
    const body = { name: f.get("name"), timezone: f.get("timezone"), message_retention_days: retention ? Number(retention) : null };
    // Shortening retention erases content: confirm first.
    const shorter = retention && (w.message_retention_days === null || Number(retention) < w.message_retention_days);
    if (shorter) setPending(body);
    else save(body);
  }

  return (
    <form onSubmit={submit} noValidate className="space-y-6">
      <Panel className="grid max-w-3xl gap-4 p-5 sm:grid-cols-2">
        <Field label="Business name" htmlFor="ws-name" error={errors.name}>
          <Input id="ws-name" name="name" defaultValue={w.name} invalid={!!errors.name} />
        </Field>
        <Field label="Time zone" htmlFor="ws-tz" error={errors.timezone} hint="Used for reports and scheduled campaigns">
          <Select id="ws-tz" name="timezone" defaultValue={w.timezone}>
            {zones().map((z) => (
              <option key={z} value={z}>
                {z}
              </option>
            ))}
          </Select>
        </Field>
      </Panel>
      <Panel className="max-w-3xl p-5">
        <h2 className="font-semibold">Message retention</h2>
        <p className="mt-1 text-sm text-muted">
          After this period, the text and files of WhatsApp messages are erased from Devwebs. The record that a message was sent, delivered or charged stays, so reports and invoices remain correct. Contacts are not affected.
        </p>
        <div className="mt-4 max-w-xs">
          <Field label="Erase message content after" htmlFor="ws-retention" error={errors.message_retention_days}>
            <Select id="ws-retention" name="retention" defaultValue={w.message_retention_days === null ? "" : String(w.message_retention_days)}>
              <option value="">{RETENTION_LABEL[""]}</option>
              {choices.map((d) => (
                <option key={d} value={d}>
                  {RETENTION_LABEL[String(d)] ?? `${d} days`}
                </option>
              ))}
            </Select>
          </Field>
        </div>
        {w.redacted_messages > 0 && <p className="mt-2 text-[13px] text-muted">{w.redacted_messages.toLocaleString("en-IN")} messages have been erased so far.</p>}
      </Panel>
      <Button type="submit" variant="primary" loading={busy && !pending}>
        Save settings
      </Button>
      <ConfirmDialog
        open={!!pending}
        title="Erase older message content?"
        message={`Messages older than ${RETENTION_LABEL[String(pending?.message_retention_days ?? "")] ?? ""} will have their text and files permanently erased within the hour. This can't be undone.`}
        confirmLabel="Save and erase"
        loading={busy}
        onConfirm={() => pending && save(pending)}
        onClose={() => setPending(null)}
      />
    </form>
  );
}

export default function WorkspaceSettingsPage() {
  const { data, reload } = useApi<{ data: Workspace; meta: { retention_choices: number[] } }>("/workspace");
  return (
    <>
      <PageHeader title="Workspace" description="Your business details and how long Devwebs keeps message content." />
      {!data ? <Skeleton className="h-80" /> : <WorkspaceForm key={`${data.data.name}-${data.data.timezone}-${data.data.message_retention_days}`} w={data.data} choices={data.meta.retention_choices} onSaved={reload} />}
    </>
  );
}
