"use client";

import type { ServerCapacityLine, ServerGroup } from "@domainops/shared-types";
import { App, Button, InputNumber, Popover, Tag, Tooltip } from "antd";
import { SettingOutlined } from "@ant-design/icons";
import { useState } from "react";
import { updateServerGroup } from "@/lib/api/servers";
import { ApiError } from "@/lib/api/client";

const STATE_COLORS: Record<ServerCapacityLine["state"], string> = {
  unlimited: "default",
  ok: "green",
  near: "gold",
  full: "red",
};

const STATE_NOTES: Record<ServerCapacityLine["state"], string> = {
  unlimited: "No limit set",
  ok: "Plenty of room",
  near: "Near the limit",
  full: "At the limit - no more accounts can be added",
};

function CapacityLine({ label, line }: { label: string; line: ServerCapacityLine }) {
  return (
    <Tooltip title={STATE_NOTES[line.state]}>
      <Tag color={STATE_COLORS[line.state]} className="!m-0 dms_servers_capacity_tag">
        {label} {line.used}
        {line.limit ? ` / ${line.limit}` : ""}
      </Tag>
    </Tooltip>
  );
}

export function CapacityCell({ group, onSaved }: { group: ServerGroup; onSaved: () => void }) {
  const { message } = App.useApp();
  const [isOpen, setIsOpen] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const [staticLimit, setStaticLimit] = useState<number | null>(group.capacity_static);
  const [wordpressLimit, setWordpressLimit] = useState<number | null>(group.capacity_wp);

  if (!group.capacity) return <span>{group.accounts_count ?? 0}</span>;

  async function handleSave() {
    setIsSaving(true);
    try {
      await updateServerGroup(group.id, { capacity_static: staticLimit, capacity_wp: wordpressLimit });
      message.success(`${group.label} limits updated.`);
      setIsOpen(false);
      onSaved();
    } catch (err) {
      message.error(err instanceof ApiError ? err.message : "Couldn't update the limits.");
    } finally {
      setIsSaving(false);
    }
  }

  return (
    <div className="flex items-center gap-2 dms_servers_capacity_cell">
      <div className="flex flex-col gap-1">
        <CapacityLine label="Static" line={group.capacity.static} />
        <CapacityLine label="WordPress" line={group.capacity.wordpress} />
      </div>
      <Popover
        trigger="click"
        open={isOpen}
        onOpenChange={(open) => {
          setIsOpen(open);
          if (open) {
            setStaticLimit(group.capacity_static);
            setWordpressLimit(group.capacity_wp);
          }
        }}
        title="Account limits"
        content={
          <div className="flex flex-col gap-3 w-64">
            <label className="flex flex-col gap-1">
              Static accounts
              <InputNumber min={1} value={staticLimit} onChange={setStaticLimit} placeholder="No limit" className="w-full" />
            </label>
            <label className="flex flex-col gap-1">
              WordPress accounts
              <InputNumber min={1} value={wordpressLimit} onChange={setWordpressLimit} placeholder="No limit" className="w-full" />
            </label>
            <div className="flex justify-end gap-2">
              <Button size="small" onClick={() => setIsOpen(false)}>
                Close
              </Button>
              <Button size="small" type="primary" loading={isSaving} onClick={() => void handleSave()}>
                Save
              </Button>
            </div>
          </div>
        }
      >
        <Tooltip title="Change the limits">
          <Button size="small" type="text" icon={<SettingOutlined />} aria-label="Change the limits" className="dms_servers_capacity_edit_btn" />
        </Tooltip>
      </Popover>
    </div>
  );
}
