import { useState } from 'react'
import { useParams } from 'react-router-dom'
import {
  useRepoSecrets, useUpsertRepoSecret, useDeleteRepoSecret,
} from '../api/queries/secrets'
import { useEnvironments } from '../api/queries/environments'
import {
  useEnvSecrets, useUpsertEnvSecret, useDeleteEnvSecret,
} from '../api/queries/secrets'
import { Skeleton } from '../ui/Skeleton'
import type { SecretListItem } from '../types/api'

// ── Shared secret table ───────────────────────────────────────────────────────

function SecretTable({
  secrets,
  onDelete,
  isLoading,
}: {
  secrets: SecretListItem[] | undefined
  onDelete: (name: string) => void
  isLoading: boolean
}) {
  if (isLoading) {
    return (
      <div className="space-y-2">
        {[1, 2].map(i => <Skeleton key={i} className="h-10 rounded" />)}
      </div>
    )
  }
  if (!secrets?.length) {
    return <p className="text-xs text-[var(--c-muted)] py-2">No secrets defined.</p>
  }
  return (
    <div className="divide-y divide-[var(--c-border)] border border-[var(--c-border)] rounded-lg overflow-hidden">
      {secrets.map(s => (
        <div key={s.id} className="flex items-center gap-3 px-4 py-2.5">
          <code className="flex-1 text-xs font-mono text-[var(--c-text)]">{s.name}</code>
          <span className="text-[10px] text-[var(--c-muted)] font-mono">••••••••</span>
          <button
            onClick={() => onDelete(s.name)}
            className="text-[var(--c-muted)] hover:text-[var(--c-danger)] transition-colors p-1"
            title="Delete secret"
          >
            <svg width="13" height="13" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0" />
            </svg>
          </button>
        </div>
      ))}
    </div>
  )
}

function AddSecretForm({
  onSubmit,
  isPending,
  error,
}: {
  onSubmit: (name: string, value: string) => void
  isPending: boolean
  error?: string
}) {
  const [name, setName] = useState('')
  const [value, setValue] = useState('')

  function submit(e: React.FormEvent) {
    e.preventDefault()
    if (!name.trim() || !value.trim()) return
    onSubmit(name.trim(), value.trim())
    setName('')
    setValue('')
  }

  return (
    <form onSubmit={submit} className="flex items-center gap-2 mt-3">
      <input
        value={name}
        onChange={e => setName(e.target.value.toUpperCase().replace(/[^A-Z0-9_]/g, '_'))}
        placeholder="SECRET_NAME"
        className="w-44 px-3 py-2 text-sm border border-[var(--c-border)] rounded-lg bg-[var(--c-surface-muted)] text-[var(--c-text)] placeholder:text-[var(--c-muted)] focus:outline-none focus:border-[var(--c-brand-focus)] font-mono"
      />
      <input
        type="password"
        value={value}
        onChange={e => setValue(e.target.value)}
        placeholder="Secret value"
        className="flex-1 px-3 py-2 text-sm border border-[var(--c-border)] rounded-lg bg-[var(--c-surface-muted)] text-[var(--c-text)] placeholder:text-[var(--c-muted)] focus:outline-none focus:border-[var(--c-brand-focus)]"
      />
      <button
        type="submit"
        disabled={!name.trim() || !value.trim() || isPending}
        className="px-3 py-2 text-sm font-medium bg-[var(--c-brand)] hover:bg-[var(--c-brand-hover)] text-white rounded-lg transition-colors disabled:opacity-50"
      >
        {isPending ? 'Saving…' : 'Save'}
      </button>
      {error && <p className="text-xs text-[var(--c-danger)]">{error}</p>}
    </form>
  )
}

// ── Env secrets sub-section ───────────────────────────────────────────────────

function EnvSecretsSection({ owner, repo, envName }: { owner: string; repo: string; envName: string }) {
  const { data: secrets, isLoading } = useEnvSecrets(owner, repo, envName)
  const upsert = useUpsertEnvSecret(owner, repo, envName)
  const del = useDeleteEnvSecret(owner, repo, envName)

  return (
    <div className="border border-[var(--c-border)] rounded-lg bg-[var(--c-surface)] overflow-hidden">
      <div className="px-4 py-3 border-b border-[var(--c-border)] bg-[var(--c-surface-raised)] flex items-center gap-2">
        <svg width="13" height="13" fill="none" stroke="var(--c-muted)" strokeWidth="1.5" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" d="M5.25 14.25h13.5m-13.5 0a3 3 0 0 1-3-3m3 3a3 3 0 1 0 6 0m-6 0H3m16.5 0a3 3 0 0 0-3-3m3 3a3 3 0 1 1-6 0m6 0h1.5m-7.5 0h-3" />
        </svg>
        <span className="text-sm font-medium text-[var(--c-text)]">{envName}</span>
        <span className="text-[10px] text-[var(--c-muted)] ml-auto">env-level override</span>
      </div>
      <div className="p-4">
        <SecretTable secrets={secrets} onDelete={name => del.mutate(name)} isLoading={isLoading} />
        <AddSecretForm
          onSubmit={(name, value) => upsert.mutate({ name, value })}
          isPending={upsert.isPending}
          error={(upsert.error as Error)?.message}
        />
      </div>
    </div>
  )
}

// ── Page ──────────────────────────────────────────────────────────────────────

export default function RepoSecretsPage() {
  const { owner = '', repo = '' } = useParams()
  const { data: repoSecrets, isLoading: loadingRepo } = useRepoSecrets(owner, repo)
  const upsertRepo = useUpsertRepoSecret(owner, repo)
  const deleteRepo = useDeleteRepoSecret(owner, repo)
  const { data: environments } = useEnvironments(owner, repo)

  return (
    <div className="max-w-3xl mx-auto px-4 md:px-6 py-5 space-y-6">
      <div>
        <h1 className="text-lg font-semibold text-[var(--c-text)]">Secrets</h1>
        <p className="text-xs text-[var(--c-muted)] mt-0.5">
          Secrets are injected as environment variables into CI pipeline jobs. Values are write-only.
        </p>
        <div className="mt-2 p-3 border border-[var(--c-border)] rounded-lg bg-[var(--c-surface-muted)] text-[10px] text-[var(--c-muted)]">
          <strong className="text-[var(--c-text)]">Priority order:</strong>{' '}
          Environment secrets → Repository secrets → Workspace secrets → Global secrets.
          Higher-priority secrets with the same name override lower ones.
        </div>
      </div>

      {/* Repository-level secrets */}
      <section>
        <h2 className="text-xs font-semibold uppercase tracking-wider text-[var(--c-muted)] mb-3">
          Repository secrets
        </h2>
        <div className="border border-[var(--c-border)] rounded-lg bg-[var(--c-surface)] overflow-hidden">
          <div className="p-4">
            <SecretTable
              secrets={repoSecrets}
              onDelete={name => deleteRepo.mutate(name)}
              isLoading={loadingRepo}
            />
            <AddSecretForm
              onSubmit={(name, value) => upsertRepo.mutate({ name, value })}
              isPending={upsertRepo.isPending}
              error={(upsertRepo.error as Error)?.message}
            />
          </div>
        </div>
      </section>

      {/* Environment-level secrets */}
      {environments && environments.length > 0 && (
        <section>
          <h2 className="text-xs font-semibold uppercase tracking-wider text-[var(--c-muted)] mb-3">
            Environment secrets
          </h2>
          <div className="space-y-3">
            {environments.map(env => (
              <EnvSecretsSection
                key={env.id}
                owner={owner}
                repo={repo}
                envName={env.name}
              />
            ))}
          </div>
        </section>
      )}
    </div>
  )
}
