import { useState } from 'react'
import { Link } from 'react-router-dom'
import { useWorkspaces, useCreateWorkspace } from '../api/queries/workspaces'
import { Skeleton } from '../ui/Skeleton'
import type { WorkspaceWithMeta } from '../types/api'

function WorkspaceCard({ ws }: { ws: WorkspaceWithMeta }) {
  return (
    <Link
      to={`/workspaces/${ws.handle}`}
      className="flex items-center gap-4 p-4 border border-[var(--c-border)] rounded-lg bg-[var(--c-surface)] hover:border-[var(--c-brand-focus)] hover:bg-[var(--c-surface-muted)] transition-colors group"
    >
      <div className="w-10 h-10 rounded-lg bg-[var(--c-brand)] flex items-center justify-center text-white text-sm font-bold shrink-0">
        {ws.displayName?.[0]?.toUpperCase() || ws.handle[0].toUpperCase()}
      </div>
      <div className="flex-1 min-w-0">
        <div className="flex items-center gap-2">
          <span className="text-sm font-semibold text-[var(--c-text)] group-hover:text-[var(--c-brand)] transition-colors">
            {ws.displayName || ws.handle}
          </span>
          <span className="text-xs font-mono text-[var(--c-muted)]">@{ws.handle}</span>
          {ws.myRole && (
            <span className="text-[10px] font-semibold px-1.5 py-px rounded border border-[var(--c-border)] text-[var(--c-muted)] capitalize">
              {ws.myRole}
            </span>
          )}
        </div>
        {ws.description && (
          <p className="text-xs text-[var(--c-muted)] mt-0.5 truncate">{ws.description}</p>
        )}
        <div className="flex items-center gap-3 mt-1 text-[10px] text-[var(--c-subtle)]">
          <span>{ws.repoCount} repo{ws.repoCount !== 1 ? 's' : ''}</span>
          <span>{ws.memberCount} member{ws.memberCount !== 1 ? 's' : ''}</span>
        </div>
      </div>
      <svg className="shrink-0 text-[var(--c-border)] group-hover:text-[var(--c-brand)] transition-colors" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" d="m8.25 4.5 7.5 7.5-7.5 7.5" />
      </svg>
    </Link>
  )
}

function CreateModal({ onClose }: { onClose: () => void }) {
  const [handle, setHandle] = useState('')
  const [displayName, setDisplayName] = useState('')
  const [description, setDescription] = useState('')
  const create = useCreateWorkspace()

  function submit(e: React.FormEvent) {
    e.preventDefault()
    if (!handle.trim()) return
    create.mutate(
      { handle: handle.trim(), displayName: displayName.trim(), description: description.trim() },
      { onSuccess: onClose },
    )
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm p-4" onClick={onClose}>
      <div className="w-full max-w-md bg-[var(--c-surface)] border border-[var(--c-border)] rounded-xl shadow-2xl" onClick={e => e.stopPropagation()}>
        <div className="flex items-center justify-between px-5 py-4 border-b border-[var(--c-border)]">
          <h2 className="text-sm font-semibold text-[var(--c-text)]">Create a workspace</h2>
          <button onClick={onClose} className="text-[var(--c-muted)] hover:text-[var(--c-text)] transition-colors">
            <svg width="16" height="16" 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>
        <form onSubmit={submit} className="p-5 space-y-4">
          <div>
            <label className="block text-xs font-medium text-[var(--c-text)] mb-1.5">
              Handle <span className="text-[var(--c-danger)]">*</span>
            </label>
            <input
              value={handle}
              onChange={e => setHandle(e.target.value.toLowerCase().replace(/[^a-z0-9_-]/g, '-'))}
              placeholder="acme-corp"
              required
              autoFocus
              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)] placeholder:text-[var(--c-muted)] focus:outline-none focus:border-[var(--c-brand-focus)] font-mono"
            />
            <p className="text-[10px] text-[var(--c-muted)] mt-1">
              Used in URLs. Letters, numbers, hyphens, underscores only.
            </p>
          </div>
          <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="Acme Corp"
              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)] placeholder:text-[var(--c-muted)] 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>
            <input
              value={description}
              onChange={e => setDescription(e.target.value)}
              placeholder="Our engineering workspace"
              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)] placeholder:text-[var(--c-muted)] focus:outline-none focus:border-[var(--c-brand-focus)]"
            />
          </div>
          {create.isError && (
            <p className="text-xs text-[var(--c-danger)]">
              {(create.error as Error)?.message ?? 'Failed to create workspace'}
            </p>
          )}
          <div className="flex gap-2 pt-1">
            <button
              type="submit"
              disabled={!handle.trim() || create.isPending}
              className="flex-1 py-2 bg-[var(--c-brand)] hover:bg-[var(--c-brand-hover)] text-white text-sm font-medium rounded-lg transition-colors disabled:opacity-50"
            >
              {create.isPending ? 'Creating…' : 'Create workspace'}
            </button>
            <button type="button" onClick={onClose} className="px-4 py-2 border border-[var(--c-border)] text-sm text-[var(--c-text)] rounded-lg hover:bg-[var(--c-surface-muted)] transition-colors">
              Cancel
            </button>
          </div>
        </form>
      </div>
    </div>
  )
}

export default function WorkspacesPage() {
  const { data: workspaces, isLoading } = useWorkspaces()
  const [showCreate, setShowCreate] = useState(false)

  return (
    <div className="max-w-3xl mx-auto px-4 md:px-6 py-5 space-y-5">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-lg font-semibold text-[var(--c-text)]">Workspaces</h1>
          <p className="text-xs text-[var(--c-muted)] mt-0.5">Shared namespaces for team repositories</p>
        </div>
        <button
          onClick={() => setShowCreate(true)}
          className="flex items-center gap-1.5 px-3 py-2 text-sm font-medium bg-[var(--c-brand)] hover:bg-[var(--c-brand-hover)] text-white rounded-lg transition-colors"
        >
          <svg width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" d="M12 4.5v15m7.5-7.5h-15" />
          </svg>
          New workspace
        </button>
      </div>

      {isLoading ? (
        <div className="space-y-3">
          {[1, 2, 3].map(i => <Skeleton key={i} className="h-20 rounded-lg" />)}
        </div>
      ) : !workspaces?.length ? (
        <div className="flex flex-col items-center justify-center py-20 border border-dashed border-[var(--c-border)] rounded-lg gap-3 text-center">
          <div className="w-10 h-10 rounded-full bg-[var(--c-surface-muted)] flex items-center justify-center">
            <svg width="20" height="20" fill="none" stroke="var(--c-muted)" strokeWidth="1.5" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" d="M18 18.72a9.094 9.094 0 0 0 3.741-.479 3 3 0 0 0-4.682-2.72m.94 3.198.001.031c0 .225-.012.447-.037.666A11.944 11.944 0 0 1 12 21c-2.17 0-4.207-.576-5.963-1.584A6.062 6.062 0 0 1 6 18.719m12 0a5.971 5.971 0 0 0-.941-3.197m0 0A5.995 5.995 0 0 0 12 12.75a5.995 5.995 0 0 0-5.058 2.772m0 0a3 3 0 0 0-4.681 2.72 8.986 8.986 0 0 0 3.74.477m.94-3.197a5.971 5.971 0 0 0-.94 3.197M15 6.75a3 3 0 1 1-6 0 3 3 0 0 1 6 0Zm6 3a2.25 2.25 0 1 1-4.5 0 2.25 2.25 0 0 1 4.5 0Zm-13.5 0a2.25 2.25 0 1 1-4.5 0 2.25 2.25 0 0 1 4.5 0Z" />
            </svg>
          </div>
          <div>
            <p className="text-sm font-medium text-[var(--c-text)]">No workspaces yet</p>
            <p className="text-xs text-[var(--c-muted)] mt-1 max-w-xs">
              Create a workspace to share repositories with your team.
            </p>
          </div>
          <button
            onClick={() => setShowCreate(true)}
            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"
          >
            Create your first workspace
          </button>
        </div>
      ) : (
        <div className="space-y-3">
          {workspaces.map(ws => <WorkspaceCard key={ws.id} ws={ws} />)}
        </div>
      )}

      {showCreate && <CreateModal onClose={() => setShowCreate(false)} />}
    </div>
  )
}
