'use client';

import { useState } from 'react';
import { useAction, useMutation, useQuery } from 'convex/react';
import { KeyRound, Trash2 } from 'lucide-react';
import { toast } from 'sonner';

import type { Id } from '@spoon/backend/convex/_generated/dataModel.js';
import { api } from '@spoon/backend/convex/_generated/api.js';
import {
  Button,
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  Input,
  Label,
} from '@spoon/ui';

export const SpoonSecretsForm = ({ spoonId }: { spoonId: Id<'spoons'> }) => {
  const secrets = useQuery(api.spoonSecrets.listForSpoon, { spoonId }) ?? [];
  const createSecret = useAction(api.spoonSecretsNode.create);
  const removeSecret = useMutation(api.spoonSecrets.remove);
  const [name, setName] = useState('');
  const [value, setValue] = useState('');
  const [description, setDescription] = useState('');
  const [saving, setSaving] = useState(false);

  const save = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setSaving(true);
    try {
      await createSecret({
        spoonId,
        name,
        value,
        description: description || undefined,
      });
      setName('');
      setValue('');
      setDescription('');
      toast.success('Spoon secret saved.');
    } catch (error) {
      console.error(error);
      toast.error('Could not save secret.');
    } finally {
      setSaving(false);
    }
  };

  return (
    <Card className='shadow-none'>
      <CardHeader>
        <CardTitle className='flex items-center gap-2 text-base'>
          <KeyRound className='size-4' />
          Project secrets
        </CardTitle>
      </CardHeader>
      <CardContent className='space-y-4'>
        <form
          onSubmit={save}
          className='grid gap-3 md:grid-cols-[1fr_1fr_1fr_auto]'
        >
          <div className='grid gap-2'>
            <Label htmlFor='secretName'>Name</Label>
            <Input
              id='secretName'
              value={name}
              placeholder='AUTHENTIK_CLIENT_ID'
              onChange={(event) => setName(event.target.value)}
            />
          </div>
          <div className='grid gap-2'>
            <Label htmlFor='secretValue'>Value</Label>
            <Input
              id='secretValue'
              type='password'
              value={value}
              onChange={(event) => setValue(event.target.value)}
            />
          </div>
          <div className='grid gap-2'>
            <Label htmlFor='secretDescription'>Description</Label>
            <Input
              id='secretDescription'
              value={description}
              placeholder='Used for local validation'
              onChange={(event) => setDescription(event.target.value)}
            />
          </div>
          <div className='flex items-end'>
            <Button type='submit' disabled={saving}>
              Save
            </Button>
          </div>
        </form>
        <div className='divide-border overflow-hidden rounded-md border'>
          {secrets.length ? (
            secrets.map((secret) => (
              <div
                key={secret._id}
                className='flex items-center justify-between gap-3 border-b p-3'
              >
                <div>
                  <p className='font-mono text-sm'>{secret.name}</p>
                  <p className='text-muted-foreground text-xs'>
                    {secret.description ?? secret.valuePreview ?? 'Configured'}
                  </p>
                </div>
                <Button
                  type='button'
                  variant='ghost'
                  size='icon'
                  aria-label={`Remove ${secret.name}`}
                  onClick={async () => {
                    await removeSecret({ secretId: secret._id });
                    toast.success('Secret removed.');
                  }}
                >
                  <Trash2 className='size-4' />
                </Button>
              </div>
            ))
          ) : (
            <p className='text-muted-foreground p-3 text-sm'>
              No secrets saved for this Spoon.
            </p>
          )}
        </div>
      </CardContent>
    </Card>
  );
};
