import {
  ApiKeyClientConfig,
  ApiKeyRecord,
  ApiKeyRightRecord,
} from "@/app/lib/api";
import { Badge } from "@/app/components/ui/badge";
import { Button } from "@/app/components/ui/button";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@/app/components/ui/card";
import { Input } from "@/app/components/ui/input";
import { Label } from "@/app/components/ui/label";
import { Textarea } from "@/app/components/ui/textarea";

type ApiKeysTabProps = {
  busy: boolean;
  adminApiKey: string;
  apiKeys: ApiKeyRecord[];
  rights: ApiKeyRightRecord[];
  apiKeyClientsConfig: ApiKeyClientConfig[];
  createdApiKeySecret: string;
  onReload: () => void;
  newApiKeyJson: string;
  onNewApiKeyJsonChange: (value: string) => void;
  onCreateApiKey: () => void;
  patchApiKeyId: string;
  onPatchApiKeyIdChange: (value: string) => void;
  patchApiKeyJson: string;
  onPatchApiKeyJsonChange: (value: string) => void;
  onUpdateApiKey: () => void;
  deleteApiKeyId: string;
  onDeleteApiKeyIdChange: (value: string) => void;
  onDeleteApiKey: () => void;
  newRightName: string;
  onNewRightNameChange: (value: string) => void;
  newRightDescription: string;
  onNewRightDescriptionChange: (value: string) => void;
  onCreateRight: () => void;
  deleteRightId: string;
  onDeleteRightIdChange: (value: string) => void;
  onDeleteRight: () => void;
  globalApiKeyEnforced: boolean;
  onGlobalApiKeyEnforcedChange: (value: boolean) => void;
  onSaveGlobalConfig: () => void;
  clientOverrideName: string;
  onClientOverrideNameChange: (value: string) => void;
  clientOverrideEnforced: boolean;
  onClientOverrideEnforcedChange: (value: boolean) => void;
  onSaveClientOverride: () => void;
  deleteClientOverrideName: string;
  onDeleteClientOverrideNameChange: (value: string) => void;
  onDeleteClientOverride: () => void;
};

export default function ApiKeysTab({
  busy,
  adminApiKey,
  apiKeys,
  rights,
  apiKeyClientsConfig,
  createdApiKeySecret,
  onReload,
  newApiKeyJson,
  onNewApiKeyJsonChange,
  onCreateApiKey,
  patchApiKeyId,
  onPatchApiKeyIdChange,
  patchApiKeyJson,
  onPatchApiKeyJsonChange,
  onUpdateApiKey,
  deleteApiKeyId,
  onDeleteApiKeyIdChange,
  onDeleteApiKey,
  newRightName,
  onNewRightNameChange,
  newRightDescription,
  onNewRightDescriptionChange,
  onCreateRight,
  deleteRightId,
  onDeleteRightIdChange,
  onDeleteRight,
  globalApiKeyEnforced,
  onGlobalApiKeyEnforcedChange,
  onSaveGlobalConfig,
  clientOverrideName,
  onClientOverrideNameChange,
  clientOverrideEnforced,
  onClientOverrideEnforcedChange,
  onSaveClientOverride,
  deleteClientOverrideName,
  onDeleteClientOverrideNameChange,
  onDeleteClientOverride,
}: ApiKeysTabProps) {
  return (
    <section className="grid h-full min-h-0 gap-4 xl:grid-cols-[1fr_430px]">
      <Card className="h-full min-h-0">
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle>API Keys</CardTitle>
            <Button
              onClick={onReload}
              size="sm"
              variant="outline"
              disabled={busy}
            >
              Reload
            </Button>
          </div>
          {createdApiKeySecret ? (
            <div className="rounded-md border border-warning-border bg-warning-subtle px-3 py-2 text-xs text-warning">
              New key secret (copy now): {createdApiKeySecret}
            </div>
          ) : null}
        </CardHeader>
        <CardContent className="grid h-[calc(100vh-220px)] min-h-0 gap-3">
          <div className="min-h-0 overflow-auto rounded-md border border-border">
            {apiKeys.map((record) => (
              <div
                key={record.id}
                className="border-b border-border p-3 text-sm"
              >
                <div className="flex items-center justify-between">
                  <p className="font-medium">{record.name}</p>
                  <Badge variant={record.is_active ? "default" : "secondary"}>
                    {record.is_active ? "active" : "inactive"}
                  </Badge>
                </div>
                <p className="text-xs text-muted-foreground">
                  {record.public_id}
                </p>
                <p className="text-xs text-muted-foreground">
                  client: {record.client_name ?? "global"}
                </p>
                <p className="text-xs text-muted-foreground">
                  rights: {record.rights.join(", ") || "none"}
                </p>
                <p className="text-xs text-muted-foreground">{record.id}</p>
              </div>
            ))}
          </div>
          <div className="grid gap-3 xl:grid-cols-2">
            <div>
              <Label className="mb-2 block">Rights</Label>
              <div className="max-h-32 overflow-auto rounded-md border border-border">
                {rights.map((right) => (
                  <div
                    key={right.id}
                    className="border-b border-border px-3 py-2 text-xs"
                  >
                    {right.name} ({right.id})
                  </div>
                ))}
              </div>
            </div>
            <div>
              <Label className="mb-2 block">Client overrides</Label>
              <div className="max-h-32 overflow-auto rounded-md border border-border">
                {apiKeyClientsConfig.map((config) => (
                  <div
                    key={config.client_name}
                    className="border-b border-border px-3 py-2 text-xs"
                  >
                    {config.client_name}: enforce_api_keys=
                    {String(config.enforce_api_keys)}
                  </div>
                ))}
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      <Card className="h-full min-h-0">
        <CardHeader>
          <CardTitle>API key actions</CardTitle>
        </CardHeader>
        <CardContent className="h-[calc(100vh-220px)] space-y-3 overflow-auto">
          <div className="space-y-2 rounded-md border border-border p-3">
            <Label>Create API key</Label>
            <Textarea
              value={newApiKeyJson}
              onChange={(event) => onNewApiKeyJsonChange(event.target.value)}
              rows={7}
              className="font-mono text-xs"
            />
            <Button
              onClick={onCreateApiKey}
              size="sm"
              disabled={busy || !adminApiKey.trim()}
            >
              Create key
            </Button>
          </div>
          <div className="space-y-2 rounded-md border border-border p-3">
            <Label>Update API key</Label>
            <Input
              value={patchApiKeyId}
              onChange={(event) => onPatchApiKeyIdChange(event.target.value)}
              placeholder="api_key id (uuid)"
            />
            <Textarea
              value={patchApiKeyJson}
              onChange={(event) => onPatchApiKeyJsonChange(event.target.value)}
              rows={5}
              className="font-mono text-xs"
            />
            <Button
              onClick={onUpdateApiKey}
              size="sm"
              variant="secondary"
              disabled={busy || !adminApiKey.trim()}
            >
              Update key
            </Button>
          </div>
          <div className="space-y-2 rounded-md border border-destructive-border p-3">
            <Label>Delete API key</Label>
            <Input
              value={deleteApiKeyId}
              onChange={(event) => onDeleteApiKeyIdChange(event.target.value)}
              placeholder="api_key id (uuid)"
            />
            <Button
              onClick={onDeleteApiKey}
              size="sm"
              variant="destructive"
              disabled={busy || !adminApiKey.trim()}
            >
              Delete key
            </Button>
          </div>
          <div className="space-y-2 rounded-md border border-border p-3">
            <Label>Create / delete right</Label>
            <Input
              value={newRightName}
              onChange={(event) => onNewRightNameChange(event.target.value)}
              placeholder="right name"
            />
            <Input
              value={newRightDescription}
              onChange={(event) =>
                onNewRightDescriptionChange(event.target.value)
              }
              placeholder="description"
            />
            <div className="flex gap-2">
              <Button
                onClick={onCreateRight}
                size="sm"
                disabled={busy || !adminApiKey.trim()}
              >
                Create right
              </Button>
              <Input
                value={deleteRightId}
                onChange={(event) => onDeleteRightIdChange(event.target.value)}
                placeholder="right id"
              />
              <Button
                onClick={onDeleteRight}
                size="sm"
                variant="destructive"
                disabled={busy || !adminApiKey.trim()}
              >
                Delete
              </Button>
            </div>
          </div>
          <div className="space-y-2 rounded-md border border-border p-3">
            <Label>Global / client enforcement</Label>
            <label className="flex items-center gap-2 text-xs text-muted-foreground">
              <input
                type="checkbox"
                checked={globalApiKeyEnforced}
                onChange={(event) =>
                  onGlobalApiKeyEnforcedChange(event.target.checked)
                }
              />
              enforce_api_keys globally
            </label>
            <Button
              onClick={onSaveGlobalConfig}
              size="sm"
              variant="secondary"
              disabled={busy || !adminApiKey.trim()}
            >
              Save global config
            </Button>
            <div className="grid grid-cols-[1fr_auto] gap-2">
              <Input
                value={clientOverrideName}
                onChange={(event) =>
                  onClientOverrideNameChange(event.target.value)
                }
                placeholder="client_name"
              />
              <select
                value={String(clientOverrideEnforced)}
                onChange={(event) =>
                  onClientOverrideEnforcedChange(event.target.value === "true")
                }
                className="h-9 rounded-md border border-border bg-surface-subtle px-2 text-xs"
              >
                <option value="true">true</option>
                <option value="false">false</option>
              </select>
            </div>
            <div className="flex gap-2">
              <Button
                onClick={onSaveClientOverride}
                size="sm"
                variant="secondary"
                disabled={busy || !adminApiKey.trim()}
              >
                Save override
              </Button>
              <Input
                value={deleteClientOverrideName}
                onChange={(event) =>
                  onDeleteClientOverrideNameChange(event.target.value)
                }
                placeholder="client_name to remove"
              />
              <Button
                onClick={onDeleteClientOverride}
                size="sm"
                variant="destructive"
                disabled={busy || !adminApiKey.trim()}
              >
                Delete
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>
    </section>
  );
}
