import { useState } from 'react';
import { useParams } from 'react-router-dom';
import { Key, Plus, Trash2 } from 'lucide-react';

import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Spinner } from '@/components/ui/spinner';
import { useAddDeployKey } from '@/hooks/repo/useAddDeployKey';
import { useDeleteDeployKey } from '@/hooks/repo/useDeleteDeployKey';
import { useRepoDeployKeys } from '@/hooks/repo/useRepoDeployKeys';
import { cn, timeAgo } from '@/lib/utils';

export function RepoDeployKeysPage() {
  const { workspaceName = '', repoName = '' } = useParams();
  const [showAdd, setShowAdd] = useState(false);
  const [title, setTitle] = useState('');
  const [publicKey, setPublicKey] = useState('');
  const [readOnly, setReadOnly] = useState(true);

  const { data: keys, isLoading } = useRepoDeployKeys(workspaceName, repoName);
  const addKey = useAddDeployKey();
  const deleteKey = useDeleteDeployKey();

  const handleAdd = () => {
    if (!title.trim() || !publicKey.trim()) return;
    const keyType = publicKey.startsWith('ssh-ed25519')
      ? 'Ed25519'
      : publicKey.startsWith('ecdsa-')
        ? 'Ecdsa'
        : 'Rsa';
    addKey.mutate(
      {
        title: title.trim(),
        public_key: publicKey.trim(),
        key_type: keyType,
        read_only: readOnly,
      },
      {
        onSuccess: () => {
          setTitle('');
          setPublicKey('');
          setReadOnly(true);
          setShowAdd(false);
        },
      },
    );
  };

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <p className="text-[12px] text-muted-foreground">
          {(keys ?? []).length} deploy key{(keys ?? []).length !== 1 ? 's' : ''}
        </p>
        <Button size="sm" onClick={() => setShowAdd(!showAdd)}>
          <Plus className="size-3.5" />
          Add deploy key
        </Button>
      </div>

      {showAdd && (
        <div className="space-y-3 rounded-lg border border-border p-4">
          <Input
            className="h-9 text-[13px]"
            placeholder="Title"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
          />
          <textarea
            className="w-full rounded-lg border border-border bg-background px-3 py-2 text-[12px] font-mono text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring"
            rows={4}
            placeholder="Paste your public key (ssh-rsa AAAA... or ssh-ed25519 AAAA...)"
            value={publicKey}
            onChange={(e) => setPublicKey(e.target.value)}
          />
          <label className="flex items-center gap-2 text-[13px]">
            <input
              type="checkbox"
              checked={readOnly}
              onChange={(e) => setReadOnly(e.target.checked)}
              className="rounded border-border"
            />
            Read-only access
          </label>
          <div className="flex gap-2">
            <Button
              size="sm"
              disabled={!title.trim() || !publicKey.trim() || addKey.isPending}
              onClick={handleAdd}
            >
              {addKey.isPending ? 'Adding...' : 'Add key'}
            </Button>
            <Button size="sm" variant="outline" onClick={() => setShowAdd(false)}>
              Cancel
            </Button>
          </div>
        </div>
      )}

      <div className="overflow-hidden rounded-lg border border-border">
        {isLoading ? (
          <div className="flex items-center justify-center py-12">
            <Spinner />
          </div>
        ) : (keys ?? []).length > 0 ? (
          <div className="divide-y divide-border">
            {(keys ?? []).map((key) => (
              <div
                key={key.id}
                className="flex items-center gap-3 px-4 py-2.5 transition-colors hover:bg-muted/40"
              >
                <Key className="size-4 shrink-0 text-muted-foreground" />
                <div className="min-w-0 flex-1">
                  <span className="text-[13px] font-medium text-foreground">{key.title}</span>
                  <div className="mt-0.5 flex items-center gap-2 text-[11px] text-muted-foreground">
                    <span className="rounded bg-muted px-1 py-0.5 text-[10px]">
                      {key.key_type}
                    </span>
                    <span
                      className={cn(
                        key.read_only ? 'text-muted-foreground' : 'text-green-600',
                      )}
                    >
                      {key.read_only ? 'Read-only' : 'Read-write'}
                    </span>
                    <code className="text-[10px] opacity-60">
                      {key.fingerprint_sha256.slice(0, 16)}...
                    </code>
                    <span>Added {timeAgo(key.created_at)}</span>
                    {key.last_used_at && (
                      <span>· Used {timeAgo(key.last_used_at)}</span>
                    )}
                  </div>
                </div>
                <Button
                  size="icon-sm"
                  variant="ghost"
                  className="text-muted-foreground hover:text-destructive"
                  onClick={() => {
                    if (confirm(`Remove deploy key "${key.title}"?`))
                      deleteKey.mutate(key.id);
                  }}
                >
                  <Trash2 className="size-3.5" />
                </Button>
              </div>
            ))}
          </div>
        ) : (
          <div className="flex flex-col items-center justify-center py-16 text-center">
            <Key className="size-6 text-muted-foreground/30" />
            <p className="mt-3 text-[13px] text-muted-foreground">No deploy keys configured</p>
            <Button size="sm" className="mt-3" onClick={() => setShowAdd(true)}>
              <Plus className="size-3.5" />
              Add first key
            </Button>
          </div>
        )}
      </div>
    </div>
  );
}
