"use client";

import type { Domain, ServerAccount } from "@domainops/shared-types";
import { App, Descriptions, Drawer, Empty, List, Skeleton, Tag, Typography } from "antd";
import Link from "next/link";
import { useCallback, useEffect, useState } from "react";
import { getServerAccount } from "@/lib/api/servers";
import { ApiError } from "@/lib/api/client";

/**
 * The drill-down from a synced (or manually added) account - what
 * previously stopped at a bare table row now opens onto what's actually
 * provisioned there, with a way to jump straight into each domain's own
 * Setup panel to assign more. Domain provisioning itself stays there, not
 * duplicated here - see ServerAccountController::show()'s docblock.
 */
export function ServerAccountDrawer({
  accountId,
  onClose,
}: {
  accountId: number | null;
  onClose: () => void;
}) {
  const { message } = App.useApp();
  const [account, setAccount] = useState<ServerAccount | null>(null);
  const [isLoading, setIsLoading] = useState(false);

  const load = useCallback(async () => {
    if (!accountId) return;
    setIsLoading(true);
    try {
      setAccount(await getServerAccount(accountId));
    } catch (err) {
      message.error(err instanceof ApiError ? err.message : "Couldn't load this account.");
    } finally {
      setIsLoading(false);
    }
  }, [accountId, message]);

  useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect
    void load();
  }, [load]);

  return (
    <Drawer
      title={account ? account.username : "Server account"}
      open={!!accountId}
      onClose={onClose}
      size={480}
      destroyOnHidden
      className="dms_server_account_drawer"
    >
      {isLoading || !account ? (
        <Skeleton active />
      ) : (
        <div className="flex flex-col gap-4">
          <Descriptions size="small" column={1}>
            <Descriptions.Item label="Server">{account.server_group?.label ?? "—"}</Descriptions.Item>
            <Descriptions.Item label="Workload">{account.workload_type}</Descriptions.Item>
            <Descriptions.Item label="WP Toolkit">{account.wp_toolkit_available ? "Yes" : "No"}</Descriptions.Item>
            <Descriptions.Item label="Current load">{account.current_load}</Descriptions.Item>
          </Descriptions>

          <div>
            <Typography.Text strong>Domains on this account</Typography.Text>
            {account.domains && account.domains.length > 0 ? (
              <List<Domain>
                size="small"
                dataSource={account.domains}
                className="dms_server_account_domains_list"
                renderItem={(domain) => (
                  <List.Item>
                    <Link href={`/domains/${domain.id}`} className="font-mono">
                      {domain.fqdn}
                    </Link>
                    <Tag>{domain.status}</Tag>
                  </List.Item>
                )}
              />
            ) : (
              <Empty
                description="No domains provisioned on this account yet - assign one from a domain's Setup panel."
                image={Empty.PRESENTED_IMAGE_SIMPLE}
                style={{ marginTop: 12 }}
              />
            )}
          </div>
        </div>
      )}
    </Drawer>
  );
}
