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

export default function ImportRepoPage() {
  const navigate = useNavigate()
  const importRepo = useImportRepo()

  const [url, setUrl] = useState('')
  const [requiresAuth, setRequiresAuth] = useState(false)
  const [authUser, setAuthUser] = useState('')
  const [authPass, setAuthPass] = useState('')
  const [name, setName] = useState('')
  const [isPrivate, setIsPrivate] = useState(true)
  const [showAdvanced, setShowAdvanced] = useState(false)
  const [description, setDescription] = useState('')

  // Auto-fill name from URL
  function handleUrlChange(val: string) {
    setUrl(val)
    if (!name) {
      const segment = val.split('/').pop()?.replace(/\.git$/, '') ?? ''
      if (segment) setName(segment)
    }
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    if (!url.trim() || !name.trim()) return
    const repo = await importRepo.mutateAsync({
      url: url.trim(),
      name: name.trim(),
      description,
      isPrivate,
      authUser: requiresAuth ? authUser : undefined,
      authPass: requiresAuth ? authPass : undefined,
    })
    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]">Import existing code</h1>
        <Link to="/repos/new" className="text-sm text-[#0052CC] hover:underline">
          Create new repository
        </Link>
      </div>
      <div className="border-t border-[#DFE1E6] mb-6" />

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

        {/* Old repository section */}
        <div>
          <h2 className="text-sm font-semibold text-[#172B4D] mb-4">Old repository</h2>
          <div className="space-y-4">
            <Field label="URL" required>
              <input
                value={url}
                onChange={e => handleUrlChange(e.target.value)}
                placeholder="https://github.com/user/repo.git"
                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]"
              />
            </Field>

            <Field label="">
              <label className="flex items-center gap-2.5 cursor-pointer">
                <input
                  type="checkbox"
                  checked={requiresAuth}
                  onChange={e => setRequiresAuth(e.target.checked)}
                  className="w-4 h-4 accent-[#0052CC]"
                />
                <span className="text-sm text-[#172B4D]">Requires authorization</span>
              </label>

              {requiresAuth && (
                <div className="mt-3 space-y-3">
                  <input
                    value={authUser}
                    onChange={e => setAuthUser(e.target.value)}
                    placeholder="Username"
                    className="w-full border border-[#DFE1E6] rounded px-3 py-2 text-sm focus:outline-none focus:border-[#4C9AFF]"
                  />
                  <input
                    type="password"
                    value={authPass}
                    onChange={e => setAuthPass(e.target.value)}
                    placeholder="Password or access token"
                    className="w-full border border-[#DFE1E6] rounded px-3 py-2 text-sm focus:outline-none focus:border-[#4C9AFF]"
                  />
                </div>
              )}
            </Field>
          </div>
        </div>

        <div className="border-t border-[#DFE1E6]" />

        {/* New repository section */}
        <div>
          <h2 className="text-sm font-semibold text-[#172B4D] mb-4">New repository</h2>
          <div className="space-y-4">

            <Field label="Repository name" required>
              <input
                value={name}
                onChange={e => setName(e.target.value.replace(/[^a-zA-Z0-9._-]/g, '-'))}
                placeholder="my-repository"
                required
                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>

            <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>

            {/* 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>
          </div>
        </div>

        {importRepo.isError && (
          <p className="text-xs text-[#DE350B]">
            {importRepo.error instanceof Error ? importRepo.error.message : 'Import failed.'}
          </p>
        )}

        {/* Footer */}
        <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={importRepo.isPending || !url.trim() || !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]"
          >
            {importRepo.isPending ? 'Importing…' : 'Import 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>
  )
}
