"use client";

import { useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { api, Workflow } from "@/lib/api";
import { Button, Card } from "@/components/ui";
import { Table, Thead, Tbody, Tr, Th, Td } from "@/components/ui";
import { resolveTargets } from "@/lib/targets";

export default function WorkflowsPage() {
    const qc = useQueryClient();
    const router = useRouter();
    const [error, setError] = useState<string | null>(null);

    const {
        data: workflows,
        isLoading,
        error: loadError,
    } = useQuery({
        queryKey: ["workflows"],
        queryFn: api.listWorkflows,
    });

    // The fleet, so a tag-only workflow reports the servers it actually reaches.
    // target_server_ids.length alone reads 0 for one, which is the count of the
    // half of the selector it does not use.
    const { data: servers } = useQuery({ queryKey: ["servers"], queryFn: () => api.listServers() });

    const { mutate: create, isPending } = useMutation({
        mutationFn: () => api.createWorkflow({ name: "Untitled workflow", target_server_ids: [], steps: [] }),
        onSuccess: (workflow) => {
            qc.invalidateQueries({ queryKey: ["workflows"] });
            router.push(`/workflows/${workflow.workflow_id}`);
        },
        onError: (err) => setError((err as Error).message),
    });

    return (
        <div className="p-4 sm:p-6 lg:p-8">
            <div className="mb-6 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                <div>
                    <h1 className="text-2xl font-bold text-text-primary">Workflows</h1>
                    <p className="mt-1 text-sm text-text-secondary">
                        {workflows?.length ?? 0} workflow{workflows?.length !== 1 ? "s" : ""} · run reusable steps across servers
                    </p>
                </div>
                <Button variant="primary" loading={isPending} onClick={() => create()}>
                    <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                        <path strokeLinecap="round" strokeLinejoin="round" d="M12 4.5v15m7.5-7.5h-15" />
                    </svg>
                    New Workflow
                </Button>
            </div>

            {error && <div className="mb-4 rounded-lg border border-danger/30 bg-danger/10 px-3 py-2 text-sm text-danger">{error}</div>}

            <Card padding={false}>
                {isLoading ? (
                    <div className="flex items-center justify-center py-20">
                        <div className="h-8 w-8 animate-spin rounded-full border-2 border-border border-t-accent" />
                    </div>
                ) : loadError ? (
                    <div className="py-20 text-center text-danger">Failed to load workflows. Is the backend running?</div>
                ) : workflows && workflows.length > 0 ? (
                    <Table>
                        <Thead>
                            <Tr>
                                <Th>Name</Th>
                                <Th>Targets</Th>
                                <Th>Steps</Th>
                                <Th>Next Run</Th>
                                <Th />
                            </Tr>
                        </Thead>
                        <Tbody>
                            {workflows.map((w: Workflow) => (
                                <Tr key={w.workflow_id}>
                                    <Td label="Name">
                                        <span className="font-medium text-text-primary">{w.name}</span>
                                    </Td>
                                    <Td label="Targets">
                                        {servers ? (
                                            (() => {
                                                const matched = resolveTargets(servers, w.target_server_ids, w.target_tags ?? {});
                                                return (
                                                    <span className="flex flex-wrap items-center gap-1.5">
                                                        <span className={matched.length === 0 ? "text-danger" : "text-text-secondary"} title={matched.map((s) => s.hostname).join("\n")}>
                                                            {matched.length} server{matched.length !== 1 ? "s" : ""}
                                                        </span>
                                                        {Object.entries(w.target_tags ?? {}).map(([k, v]) => (
                                                            <span key={k} className="rounded-sm border border-border px-1.5 py-0.5 font-mono text-[10px] text-text-tertiary">
                                                                {k}:{v}
                                                            </span>
                                                        ))}
                                                    </span>
                                                );
                                            })()
                                        ) : (
                                            <span className="text-text-tertiary">…</span>
                                        )}
                                    </Td>
                                    <Td label="Steps">
                                        <span className="text-text-secondary">{w.steps.length}</span>
                                    </Td>
                                    <Td label="Next Run">
                                        {w.next_run_at && w.schedule?.enabled ? (
                                            <span className="font-mono text-[11px] text-text-tertiary">{new Date(w.next_run_at).toLocaleString()}</span>
                                        ) : (
                                            <span className="font-mono text-[11px] text-text-tertiary">No Schedule Set</span>
                                        )}
                                    </Td>
                                    <Td>
                                        <div className="flex items-center justify-end gap-2">
                                            <Link href={`/workflows/${w.workflow_id}/runs`}>
                                                <Button variant="ghost" size="sm">
                                                    Runs
                                                </Button>
                                            </Link>
                                            <Link href={`/workflows/${w.workflow_id}`}>
                                                <Button variant="ghost" size="sm">
                                                    Open →
                                                </Button>
                                            </Link>
                                        </div>
                                    </Td>
                                </Tr>
                            ))}
                        </Tbody>
                    </Table>
                ) : (
                    <div className="py-20 text-center">
                        <div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-surface-2">
                            <svg className="h-6 w-6 text-text-secondary" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                                <path strokeLinecap="round" strokeLinejoin="round" d="M9.594 3.94c.09-.542.56-.94 1.11-.94h2.593c.55 0 1.02.398 1.11.94l.213 1.281M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                            </svg>
                        </div>
                        <p className="text-text-secondary">No workflows yet.</p>
                        <Button variant="primary" size="sm" className="mt-4" loading={isPending} onClick={() => create()}>
                            Create your first workflow
                        </Button>
                    </div>
                )}
            </Card>
        </div>
    );
}
