import { useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { useCreateRepo } from '../api/queries/repos'

export default function CreateRepoPage() {
  const navigate = useNavigate()
  const createRepo = useCreateRepo()

  const [name, setName] = useState('')
  const [isPrivate, setIsPrivate] = useState(true)
  const [initReadme, setInitReadme] = useState<'none' | 'blank' | 'tutorial'>('none')
  const [defaultBranch, setDefaultBranch] = useState('')
  const [initGitignore, setInitGitignore] = useState(true)
  const [showAdvanced, setShowAdvanced] = useState(false)
  const [description, setDescription] = useState('')

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    if (!name.trim()) return
    const repo = await createRepo.mutateAsync({
      name: name.trim(),
      description,
      isPrivate,
      defaultBranch: defaultBranch.trim() || 'main',
      initReadme,
      initGitignore,
    })
    navigate(`/repos/${repo.ownerName}/${repo.name}`)
  }

  return (
    <div className="max-w-2xl mx-auto px-4 py-10">
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-xl font-semibold text-[#172B4D]">Create a new repository</h1>
        <Link to="/repos/import" className="text-sm text-[#0052CC] hover:underline">
          Import repository
        </Link>
      </div>
      <div className="border-t border-[#DFE1E6] mb-6" />

      <form onSubmit={handleSubmit} className="space-y-5">

        {/* Repository name */}
        <Field label="Repository name" required>
          <input
            value={name}
            onChange={e => setName(e.target.value.replace(/[^a-zA-Z0-9._-]/g, '-'))}
            placeholder="my-repository"
            required
            autoFocus
            className="w-full border border-[#DFE1E6] rounded px-3 py-2 text-sm focus:outline-none focus:border-[#4C9AFF] focus:ring-1 focus:ring-[#4C9AFF]"
          />
          {name && !/^[a-zA-Z0-9._-]+$/.test(name) && (
            <p className="text-xs text-[#DE350B] mt-1">Only letters, numbers, hyphens, underscores and dots are allowed.</p>
          )}
        </Field>

        {/* Access level */}
        <Field label="Access level">
          <label className="flex items-start gap-2.5 cursor-pointer">
            <input
              type="checkbox"
              checked={isPrivate}
              onChange={e => setIsPrivate(e.target.checked)}
              className="mt-0.5 w-4 h-4 accent-[#0052CC]"
            />
            <div>
              <span className="text-sm font-medium text-[#172B4D]">Private repository</span>
              <p className="text-xs text-[#0052CC] mt-0.5 leading-relaxed">
                {isPrivate
                  ? 'Uncheck to make this repository public. Public repositories typically contain open-source code and can be viewed by anyone.'
                  : 'Check to make this repository private. Only invited collaborators can see and push to it.'}
              </p>
            </div>
          </label>
        </Field>

        {/* Include README */}
        <Field label="Include a README?">
          <select
            value={initReadme}
            onChange={e => setInitReadme(e.target.value as 'none' | 'blank' | 'tutorial')}
            className="w-full border border-[#DFE1E6] rounded px-3 py-2 text-sm focus:outline-none focus:border-[#4C9AFF] bg-white"
          >
            <option value="none">No</option>
            <option value="blank">Yes, blank</option>
            <option value="tutorial">Yes, with a tutorial (for beginners)</option>
          </select>
        </Field>

        {/* Default branch */}
        <Field label="Default branch name">
          <input
            value={defaultBranch}
            onChange={e => setDefaultBranch(e.target.value)}
            placeholder="e.g., 'main'"
            className="w-full border border-[#DFE1E6] rounded px-3 py-2 text-sm focus:outline-none focus:border-[#4C9AFF] focus:ring-1 focus:ring-[#4C9AFF]"
          />
        </Field>

        {/* Include .gitignore */}
        <Field label="Include .gitignore?">
          <select
            value={initGitignore ? 'yes' : 'no'}
            onChange={e => setInitGitignore(e.target.value === 'yes')}
            className="w-full border border-[#DFE1E6] rounded px-3 py-2 text-sm focus:outline-none focus:border-[#4C9AFF] bg-white"
          >
            <option value="yes">Yes (recommended)</option>
            <option value="no">No</option>
          </select>
        </Field>

        {/* Advanced settings */}
        <div>
          <button
            type="button"
            onClick={() => setShowAdvanced(s => !s)}
            className="flex items-center gap-1.5 text-sm text-[#0052CC] hover:underline font-medium"
          >
            <svg
              width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2.5" viewBox="0 0 24 24"
              className={`transition-transform ${showAdvanced ? 'rotate-180' : ''}`}
            >
              <path strokeLinecap="round" strokeLinejoin="round" d="m19.5 8.25-7.5 7.5-7.5-7.5" />
            </svg>
            Advanced settings
          </button>

          {showAdvanced && (
            <div className="mt-4 space-y-4 border-t border-[#DFE1E6] pt-4">
              <Field label="Description">
                <textarea
                  value={description}
                  onChange={e => setDescription(e.target.value)}
                  rows={4}
                  className="w-full border border-[#DFE1E6] rounded px-3 py-2 text-sm focus:outline-none focus:border-[#4C9AFF] resize-y"
                  placeholder="Describe your repository…"
                />
              </Field>
            </div>
          )}
        </div>

        {createRepo.isError && (
          <p className="text-xs text-[#DE350B]">
            {createRepo.error instanceof Error ? createRepo.error.message : 'Failed to create repository.'}
          </p>
        )}

        {/* Footer actions */}
        <div className="border-t border-[#DFE1E6] pt-5 flex items-center justify-end gap-3">
          <Link
            to="/repos"
            className="px-4 py-2 rounded border border-[#DFE1E6] text-sm text-[#172B4D] hover:bg-[#F4F5F7] min-h-[36px] flex items-center"
          >
            Cancel
          </Link>
          <button
            type="submit"
            disabled={createRepo.isPending || !name.trim()}
            className="px-4 py-2 rounded bg-[#0052CC] text-white text-sm font-medium hover:bg-[#0065FF] disabled:opacity-50 min-h-[36px]"
          >
            {createRepo.isPending ? 'Creating…' : 'Create repository'}
          </button>
        </div>
      </form>
    </div>
  )
}

function Field({ label, required, children }: { label: string; required?: boolean; children: React.ReactNode }) {
  return (
    <div className="grid grid-cols-[180px_1fr] gap-4 items-start">
      <label className="text-sm text-[#172B4D] text-right pt-2 leading-tight">
        {label}{required && <span className="text-[#DE350B] ml-0.5">*</span>}
      </label>
      <div>{children}</div>
    </div>
  )
}
