"use client";

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

const inputClass =
  "w-full rounded-lg border border-border bg-surface-2 px-3 py-2 text-sm text-text-primary placeholder-text-secondary/50 focus:border-accent focus:outline-none focus:ring-1 focus:ring-accent";

function NewGroupModal({ onClose }: { onClose: () => void }) {
  const queryClient = useQueryClient();
  const [group, setGroup] = useState("");
  const [key, setKey] = useState("");
  const [value, setValue] = useState("");

  const { mutate: create, isPending, error } = useMutation({
    mutationFn: () =>
      api.createSecretGroup(group.trim(), { [key.trim()]: value }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["secret-groups"] });
      onClose();
    },
  });

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4 backdrop-blur-sm">
      <div className="w-full max-w-lg rounded-xl border border-border bg-surface p-6">
        <h2 className="mb-1 text-lg font-semibold text-text-primary">New Secret Group</h2>
        <p className="mb-4 text-sm text-text-secondary">
          A group must be created with at least one key. You can add more keys afterwards.
        </p>

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

        <div className="space-y-4">
          <div>
            <label className="mb-1.5 block text-sm font-medium text-text-secondary">Group name</label>
            <input
              type="text"
              value={group}
              onChange={(e) => setGroup(e.target.value)}
              placeholder="e.g. myapp-prod"
              className={`${inputClass} font-mono`}
            />
          </div>
          <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
            <div>
              <label className="mb-1.5 block text-sm font-medium text-text-secondary">First key</label>
              <input
                type="text"
                value={key}
                onChange={(e) => setKey(e.target.value)}
                placeholder="DB_PASSWORD"
                className={`${inputClass} font-mono`}
              />
            </div>
            <div>
              <label className="mb-1.5 block text-sm font-medium text-text-secondary">Value</label>
              <input
                type="text"
                value={value}
                onChange={(e) => setValue(e.target.value)}
                placeholder="supersecret123"
                className={`${inputClass} font-mono`}
              />
            </div>
          </div>
        </div>

        <div className="mt-6 flex justify-end gap-3">
          <Button variant="ghost" onClick={onClose}>Cancel</Button>
          <Button
            variant="primary"
            loading={isPending}
            disabled={!group.trim() || !key.trim() || !value}
            onClick={() => create()}
          >
            Create Group
          </Button>
        </div>
      </div>
    </div>
  );
}

export default function SecretsPage() {
  const [showNew, setShowNew] = useState(false);

  const { data: groups, isLoading, error } = useQuery({
    queryKey: ["secret-groups"],
    queryFn: api.listSecretGroups,
  });

  return (
    <div className="p-4 sm:p-6 lg:p-8">
      {showNew && <NewGroupModal onClose={() => setShowNew(false)} />}

      <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">Secrets</h1>
          <p className="mt-1 text-sm text-text-secondary">
            {groups?.length ?? 0} group{groups?.length !== 1 ? "s" : ""} · encrypted at rest, exposed to Kubernetes via ESO
          </p>
        </div>
        <Button variant="primary" onClick={() => setShowNew(true)}>
          <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 Group
        </Button>
      </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>
        ) : error ? (
          <div className="py-20 text-center text-danger">
            Failed to load secrets. Is the backend running?
          </div>
        ) : groups && groups.length > 0 ? (
          <Table>
            <Thead>
              <Tr>
                <Th>Group</Th>
                <Th>Keys</Th>
                <Th>Last Updated</Th>
                <Th />
              </Tr>
            </Thead>
            <Tbody>
              {groups.map((g: SecretGroupSummary) => (
                <Tr key={g.group}>
                  <Td label="Group">
                    <span className="font-mono font-medium text-text-primary">{g.group}</span>
                  </Td>
                  <Td label="Keys">
                    <span className="text-text-secondary">
                      {g.key_count} key{g.key_count !== 1 ? "s" : ""}
                    </span>
                  </Td>
                  <Td label="Last Updated">
                    <span className="text-text-secondary text-xs">
                      {new Date(g.updated_at).toLocaleString()}
                    </span>
                  </Td>
                  <Td>
                    <Link href={`/secrets/${encodeURIComponent(g.group)}`}>
                      <Button variant="ghost" size="sm">View →</Button>
                    </Link>
                  </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="M16.5 10.5V6.75a4.5 4.5 0 10-9 0v3.75m-.75 11.25h10.5a2.25 2.25 0 002.25-2.25v-6.75a2.25 2.25 0 00-2.25-2.25H6.75a2.25 2.25 0 00-2.25 2.25v6.75a2.25 2.25 0 002.25 2.25z" />
              </svg>
            </div>
            <p className="text-text-secondary">No secret groups yet.</p>
            <Button variant="primary" size="sm" className="mt-4" onClick={() => setShowNew(true)}>
              Create your first group
            </Button>
          </div>
        )}
      </Card>
    </div>
  );
}
