import { useState } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import {
  useWorkspace, useWorkspaceMembers, useUpdateWorkspace,
  useDeleteWorkspace, useAddWorkspaceMember, useUpdateWorkspaceMember,
  useRemoveWorkspaceMember,
} from '../api/queries/workspaces'
import {
  useWorkspaceSecrets, useUpsertWorkspaceSecret, useDeleteWorkspaceSecret,
} from '../api/queries/secrets'
import { Skeleton } from '../ui/Skeleton'
import type { WorkspaceMember } from '../types/api'

// ── Shared section wrapper ───────────────────────────────────────────────────

function Section({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <section 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)]">
        <h2 className="text-sm font-semibold text-[var(--c-text)]">{title}</h2>
      </div>
      <div className="p-4">{children}</div>
    </section>
  )
}

// ── General settings ─────────────────────────────────────────────────────────

function GeneralSection({ handle }: { handle: string }) {
  const { data: ws } = useWorkspace(handle)
  const update = useUpdateWorkspace(handle)
  const [displayName, setDisplayName] = useState(ws?.displayName ?? '')
  const [description, setDescription] = useState(ws?.description ?? '')

  function submit(e: React.FormEvent) {
    e.preventDefault()
    update.mutate({ displayName, description })
  }

  return (
    <Section title="General">
      <form onSubmit={submit} className="space-y-4">
        <div>
          <label className="block text-xs font-medium text-[var(--c-text)] mb-1.5">Display name</label>
          <input
            value={displayName}
            onChange={e => setDisplayName(e.target.value)}
            placeholder={handle}
            className="w-full px-3 py-2 text-sm border border-[var(--c-border)] rounded-lg bg-[var(--c-surface-muted)] text-[var(--c-text)] focus:outline-none focus:border-[var(--c-brand-focus)]"
          />
        </div>
        <div>
          <label className="block text-xs font-medium text-[var(--c-text)] mb-1.5">Description</label>
          <textarea
            value={description}
            onChange={e => setDescription(e.target.value)}
            rows={3}
            className="w-full px-3 py-2 text-sm border border-[var(--c-border)] rounded-lg bg-[var(--c-surface-muted)] text-[var(--c-text)] focus:outline-none focus:border-[var(--c-brand-focus)] resize-y"
          />
        </div>
        <button
          type="submit"
          disabled={update.isPending}
          className="px-4 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"
        >
          {update.isPending ? 'Saving…' : 'Save changes'}
        </button>
      </form>
    </Section>
  )
}

// ── Members ───────────────────────────────────────────────────────────────────

function MembersSection({ handle, myRole }: { handle: string; myRole: string }) {
  const { data: members } = useWorkspaceMembers(handle)
  const addMember = useAddWorkspaceMember(handle)
  const updateMember = useUpdateWorkspaceMember(handle)
  const removeMember = useRemoveWorkspaceMember(handle)
  const [username, setUsername] = useState('')
  const [role, setRole] = useState('member')
  const canEdit = myRole === 'owner' || myRole === 'admin'

  function add(e: React.FormEvent) {
    e.preventDefault()
    if (!username.trim()) return
    addMember.mutate({ username: username.trim(), role }, { onSuccess: () => setUsername('') })
  }

  const ROLES = ['owner', 'admin', 'member']
  const roleBadge: Record<string, string> = {
    owner: 'bg-[var(--c-brand-tint)] text-[var(--c-brand)] border-[var(--c-brand-focus)]',
    admin: 'bg-[#FFFAE6] text-[#B45309] border-[#F59E0B]/40',
    member: 'bg-[var(--c-surface-muted)] text-[var(--c-muted)] border-[var(--c-border)]',
  }

  return (
    <Section title="Members">
      <div className="space-y-3">
        {/* Member list */}
        <div className="divide-y divide-[var(--c-border)] border border-[var(--c-border)] rounded-lg overflow-hidden">
          {!members?.length ? (
            <p className="px-4 py-3 text-xs text-[var(--c-muted)]">No members.</p>
          ) : (
            members.map((m: WorkspaceMember) => (
              <div key={m.id} className="flex items-center gap-3 px-4 py-2.5">
                <div className="w-7 h-7 rounded-full bg-[var(--c-brand)] flex items-center justify-center text-white text-[11px] font-bold shrink-0">
                  {m.username[0].toUpperCase()}
                </div>
                <span className="flex-1 text-sm text-[var(--c-text)]">{m.username}</span>
                {canEdit ? (
                  <select
                    value={m.role}
                    onChange={e => updateMember.mutate({ username: m.username, role: e.target.value })}
                    className="text-xs border border-[var(--c-border)] rounded px-2 py-1 bg-[var(--c-surface)] text-[var(--c-text)] focus:outline-none focus:border-[var(--c-brand-focus)]"
                  >
                    {ROLES.map(r => <option key={r} value={r}>{r}</option>)}
                  </select>
                ) : (
                  <span className={`text-[10px] font-semibold px-2 py-0.5 rounded border capitalize ${roleBadge[m.role] || roleBadge.member}`}>
                    {m.role}
                  </span>
                )}
                {canEdit && (
                  <button
                    onClick={() => removeMember.mutate(m.username)}
                    className="text-[var(--c-muted)] hover:text-[var(--c-danger)] transition-colors p-1"
                    title="Remove member"
                  >
                    <svg width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
                    </svg>
                  </button>
                )}
              </div>
            ))
          )}
        </div>

        {/* Add member form */}
        {canEdit && (
          <form onSubmit={add} className="flex items-center gap-2">
            <input
              value={username}
              onChange={e => setUsername(e.target.value)}
              placeholder="Username to add"
              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)]"
            />
            <select
              value={role}
              onChange={e => setRole(e.target.value)}
              className="px-2 py-2 text-sm border border-[var(--c-border)] rounded-lg bg-[var(--c-surface)] text-[var(--c-text)] focus:outline-none focus:border-[var(--c-brand-focus)]"
            >
              <option value="member">Member</option>
              <option value="admin">Admin</option>
            </select>
            <button
              type="submit"
              disabled={!username.trim() || addMember.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"
            >
              Add
            </button>
          </form>
        )}
        {addMember.isError && (
          <p className="text-xs text-[var(--c-danger)]">{(addMember.error as Error)?.message}</p>
        )}
      </div>
    </Section>
  )
}

// ── Secrets ───────────────────────────────────────────────────────────────────

function SecretsSection({ handle }: { handle: string }) {
  const { data: secrets } = useWorkspaceSecrets(handle)
  const upsert = useUpsertWorkspaceSecret(handle)
  const del = useDeleteWorkspaceSecret(handle)
  const [name, setName] = useState('')
  const [value, setValue] = useState('')

  function submit(e: React.FormEvent) {
    e.preventDefault()
    if (!name.trim() || !value.trim()) return
    upsert.mutate({ name: name.trim(), value: value.trim() }, {
      onSuccess: () => { setName(''); setValue('') },
    })
  }

  return (
    <Section title="Secrets">
      <p className="text-xs text-[var(--c-muted)] mb-3">
        Secrets are available to all CI pipelines in this workspace's repositories. Values are write-only and never displayed after creation.
      </p>
      <div className="space-y-3">
        <div className="divide-y divide-[var(--c-border)] border border-[var(--c-border)] rounded-lg overflow-hidden">
          {!secrets?.length ? (
            <p className="px-4 py-3 text-xs text-[var(--c-muted)]">No workspace secrets.</p>
          ) : (
            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)]">••••••••</span>
                <button
                  onClick={() => del.mutate(s.name)}
                  className="text-[var(--c-muted)] hover:text-[var(--c-danger)] transition-colors p-1"
                >
                  <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>
        <form onSubmit={submit} className="flex items-center gap-2">
          <input
            value={name}
            onChange={e => setName(e.target.value.toUpperCase().replace(/[^A-Z0-9_]/g, '_'))}
            placeholder="SECRET_NAME"
            className="w-40 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() || upsert.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"
          >
            Save
          </button>
        </form>
      </div>
    </Section>
  )
}

// ── Danger zone ───────────────────────────────────────────────────────────────

function DangerSection({ handle, myRole }: { handle: string; myRole: string }) {
  const del = useDeleteWorkspace(handle)
  const navigate = useNavigate()

  if (myRole !== 'owner') return null

  return (
    <Section title="Danger zone">
      <div className="flex items-center justify-between gap-4 p-3 border border-[var(--c-danger)]/30 rounded-lg bg-[var(--c-danger-tint)]">
        <div>
          <p className="text-sm font-medium text-[var(--c-text)]">Delete workspace</p>
          <p className="text-xs text-[var(--c-muted)] mt-0.5">
            Permanently deletes the workspace and all membership. Repos must be deleted first.
          </p>
        </div>
        <button
          onClick={() => {
            if (confirm(`Delete workspace "${handle}"? This cannot be undone.`)) {
              del.mutate(undefined, { onSuccess: () => navigate('/workspaces') })
            }
          }}
          disabled={del.isPending}
          className="px-3 py-2 text-sm font-medium border border-[var(--c-danger)] text-[var(--c-danger)] rounded-lg hover:bg-[var(--c-danger)] hover:text-white transition-colors disabled:opacity-50 shrink-0"
        >
          Delete
        </button>
      </div>
    </Section>
  )
}

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

export default function WorkspaceSettingsPage() {
  const { handle = '' } = useParams()
  const { data: ws, isLoading } = useWorkspace(handle)

  if (isLoading) {
    return (
      <div className="max-w-3xl mx-auto px-4 md:px-6 py-5 space-y-4">
        {[1, 2, 3].map(i => <Skeleton key={i} className="h-40 rounded-lg" />)}
      </div>
    )
  }

  if (!ws) {
    return <div className="p-6 text-sm text-[var(--c-muted)]">Workspace not found.</div>
  }

  const canAdmin = ws.myRole === 'owner' || ws.myRole === 'admin'

  return (
    <div className="max-w-3xl mx-auto px-4 md:px-6 py-5 space-y-5">
      <div>
        <h1 className="text-lg font-semibold text-[var(--c-text)]">
          {ws.displayName || ws.handle} — Settings
        </h1>
        <p className="text-xs text-[var(--c-muted)] mt-0.5 font-mono">@{ws.handle}</p>
      </div>

      {canAdmin && <GeneralSection handle={handle} />}
      <MembersSection handle={handle} myRole={ws.myRole} />
      {canAdmin && <SecretsSection handle={handle} />}
      <DangerSection handle={handle} myRole={ws.myRole} />
    </div>
  )
}
