"use client";

import { useState } from "react";
import { api, ServerWithKeys } from "@/lib/api";
import { Badge, Button, Card, Table, Tbody, Td, Th, Thead, Tr } from "@/components/ui";

/*
 * Everything that changes what is installed on the machine: its OS packages,
 * its agent, and its existence.
 *
 * The OS update list is a panel here rather than the modal it used to be. A
 * modal made the list a detour off a header button; the work of patching a
 * server is the reason this tab exists, so the list is the tab.
 */

export function MaintenanceTab({
    server,
    latestVersion,
    onApplyUpdates,
    isApplying,
    applySuccess,
    onUpdateAgent,
    isUpdatingAgent,
    updateAgentSuccess,
    onDelete,
    isDeleting,
}: {
    server: ServerWithKeys;
    latestVersion?: string;
    onApplyUpdates: () => void;
    isApplying: boolean;
    applySuccess: boolean;
    onUpdateAgent: () => void;
    isUpdatingAgent: boolean;
    updateAgentSuccess: boolean;
    onDelete: () => void;
    isDeleting: boolean;
}) {
    const [copied, setCopied] = useState(false);
    const [confirmDelete, setConfirmDelete] = useState(false);

    const updates = server.available_updates ?? [];
    const command = api.getUpdateCommand(server.os_info);
    const isWindows = server.os_info?.toLowerCase().includes("windows");
    const agentCurrent = !!latestVersion && !!server.agent_version && server.agent_version === latestVersion;

    return (
        <div className="grid grid-cols-1 gap-6 xl:grid-cols-2">
            <Card padding={false}>
                <div className="flex flex-wrap items-center justify-between gap-3 border-b border-border px-6 py-4">
                    <h2 className="text-lg font-semibold text-text-primary">OS updates</h2>
                    {updates.length > 0 ? <Badge variant="warning">{updates.length} pending</Badge> : <Badge variant="success">up to date</Badge>}
                </div>

                {updates.length === 0 ? (
                    <p className="px-6 py-10 text-center text-sm text-text-secondary">No pending package updates. The agent checks hourly.</p>
                ) : (
                    <>
                        {/* Capped so a host with 400 pending packages does not make the
                            Apply button a scroll away. The count is on the badge. */}
                        <div className="max-h-80 overflow-y-auto">
                            <Table>
                                <Thead>
                                    <Tr>
                                        <Th>Package</Th>
                                        <Th>Current</Th>
                                        <Th>Available</Th>
                                    </Tr>
                                </Thead>
                                <Tbody>
                                    {updates.map((u) => (
                                        <Tr key={u.name}>
                                            <Td label="Package">
                                                <span className="font-mono text-sm font-medium">{u.name}</span>
                                            </Td>
                                            <Td label="Current">
                                                <span className="font-mono text-xs text-text-secondary">{u.current_version || "n/a"}</span>
                                            </Td>
                                            <Td label="Available">
                                                <span className="font-mono text-xs text-success">{u.new_version}</span>
                                            </Td>
                                        </Tr>
                                    ))}
                                </Tbody>
                            </Table>
                        </div>

                        <div className="flex flex-wrap items-center gap-3 border-t border-border px-6 py-4">
                            <Button variant="primary" loading={isApplying} onClick={onApplyUpdates} disabled={server.status !== "active"} title={server.status !== "active" ? "Agent must be online to apply updates" : undefined}>
                                {applySuccess ? "Sent!" : "Apply updates"}
                            </Button>
                            <p className="text-xs text-text-tertiary">Upgrade runs in the background and may take several minutes.</p>
                        </div>
                    </>
                )}
            </Card>

            <div className="space-y-6">
                <Card padding={false}>
                    <div className="flex flex-wrap items-center justify-between gap-3 border-b border-border px-6 py-4">
                        <h2 className="text-lg font-semibold text-text-primary">Agent</h2>
                        {latestVersion && server.agent_version && <Badge variant={agentCurrent ? "success" : "warning"}>{agentCurrent ? "up to date" : "update available"}</Badge>}
                    </div>

                    <div className="space-y-4 px-6 py-5">
                        <div className="flex flex-wrap items-center gap-x-6 gap-y-2 text-sm">
                            <div>
                                <span className="text-text-secondary">Installed: </span>
                                <span className="font-mono font-medium text-text-primary">{server.agent_version ? `v${server.agent_version}` : "unknown"}</span>
                            </div>
                            <div>
                                <span className="text-text-secondary">Latest: </span>
                                <span className="font-mono font-medium text-text-primary">{latestVersion ? `v${latestVersion}` : "n/a"}</span>
                            </div>
                        </div>

                        <div className="relative overflow-x-auto rounded border border-border bg-well px-4 py-2.5 font-mono text-sm">
                            <span className="text-accent">{isWindows ? "PS>" : "$"}</span> <span className="text-text-primary">{command}</span>
                            <button
                                onClick={async () => {
                                    await navigator.clipboard.writeText(command);
                                    setCopied(true);
                                    setTimeout(() => setCopied(false), 2000);
                                }}
                                className="absolute right-2 top-1.5 rounded border border-border bg-surface-2 px-2 py-0.5 text-xs font-medium text-text-secondary transition-colors hover:border-accent/50 hover:text-text-primary"
                            >
                                {copied ? <span className="text-success">Copied!</span> : "Copy"}
                            </button>
                        </div>

                        <Button
                            variant="primary"
                            loading={isUpdatingAgent}
                            onClick={onUpdateAgent}
                            disabled={server.status !== "active"}
                            title={server.status !== "active" ? "Agent must be online to update" : undefined}
                        >
                            {updateAgentSuccess ? "Update sent!" : "Update agent"}
                        </Button>
                    </div>
                </Card>

                <Card padding={false} className="border-danger/30">
                    <div className="border-b border-danger/30 px-6 py-4">
                        <h2 className="text-lg font-semibold text-danger">Remove server</h2>
                    </div>
                    <div className="space-y-4 px-6 py-5">
                        <p className="text-sm text-text-secondary">
                            Deletes this server and its history from Vantage. The agent stays installed on the machine and keeps trying to connect until you uninstall it there.
                        </p>
                        {!confirmDelete ? (
                            <Button variant="danger" onClick={() => setConfirmDelete(true)}>
                                Remove server
                            </Button>
                        ) : (
                            <div className="flex flex-wrap items-center gap-3">
                                <span className="text-sm text-danger">Remove {server.hostname}?</span>
                                <Button variant="danger" loading={isDeleting} onClick={onDelete}>
                                    Confirm
                                </Button>
                                <Button variant="ghost" onClick={() => setConfirmDelete(false)}>
                                    Cancel
                                </Button>
                            </div>
                        )}
                    </div>
                </Card>
            </div>
        </div>
    );
}
