import { useState, useEffect } from 'react'
import { useParams, useNavigate, Link } from 'react-router-dom'
import { useRepo, useRepoBranches } from '../api/queries/repos'
import { useCreatePR } from '../api/queries/prs'
import { useDefaultDescription } from '../api/queries/prs'
import { Skeleton } from '../ui/Skeleton'

export default function CreatePRPage() {
  const { owner = '', repo: repoName = '' } = useParams<{ owner: string; repo: string }>()
  const navigate = useNavigate()

  const { data: repoData, isLoading: repoLoading } = useRepo(owner, repoName)
  const { data: branches = [], isLoading: branchesLoading } = useRepoBranches(owner, repoName)
  const { data: descData } = useDefaultDescription(owner, repoName)
  const createPR = useCreatePR(owner, repoName)

  const [title, setTitle] = useState('')
  const [body, setBody] = useState('')
  const [sourceBranch, setSourceBranch] = useState('')
  const [targetBranch, setTargetBranch] = useState('')
  const [error, setError] = useState('')

  // Pre-fill target branch from repo default and body from template
  useEffect(() => {
    if (repoData && !targetBranch) setTargetBranch(repoData.defaultBranch)
  }, [repoData])

  useEffect(() => {
    if (descData?.template && !body) setBody(descData.template)
  }, [descData])

  const isLoading = repoLoading || branchesLoading

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    setError('')

    if (!title.trim()) { setError('Title is required.'); return }
    if (!sourceBranch) { setError('Source branch is required.'); return }
    if (!targetBranch) { setError('Target branch is required.'); return }
    if (sourceBranch === targetBranch) { setError('Source and target branch must be different.'); return }

    try {
      const pr = await createPR.mutateAsync({
        title: title.trim(),
        body,
        sourceBranch,
        targetBranch,
      })
      navigate(`/repos/${owner}/${repoName}/pulls/${pr.id}`)
    } catch (err: any) {
      setError(err.message ?? 'Failed to create pull request.')
    }
  }

  if (isLoading) {
    return (
      <div className="max-w-2xl mx-auto px-4 md:px-6 py-6 space-y-4">
        <Skeleton className="h-5 w-48 rounded" />
        <Skeleton className="h-10 rounded" />
        <Skeleton className="h-10 rounded" />
        <Skeleton className="h-32 rounded" />
      </div>
    )
  }

  const branchOptions = branches.map(b => b.name)
  const isEmpty = repoData?.isEmpty ?? false

  return (
    <div className="max-w-2xl mx-auto px-4 md:px-6 py-6 space-y-6">
      {/* Breadcrumb */}
      <div className="flex items-center gap-1 text-sm">
        <Link to={`/repos/${owner}/${repoName}`} className="text-[var(--c-brand)] hover:underline">{repoName}</Link>
        <span className="text-[var(--c-muted)]">/</span>
        <Link to={`/repos/${owner}/${repoName}/pulls`} className="text-[var(--c-brand)] hover:underline">Pull requests</Link>
        <span className="text-[var(--c-muted)]">/</span>
        <span className="font-semibold text-[var(--c-text)]">New</span>
      </div>

      <div>
        <h1 className="text-xl font-semibold text-[var(--c-text)]">Open a pull request</h1>
        <p className="text-sm text-[var(--c-muted)] mt-1">Propose changes by selecting branches to merge.</p>
      </div>

      {isEmpty ? (
        <div className="rounded-lg border border-[var(--c-border)] p-8 text-center space-y-2">
          <p className="text-sm font-medium text-[var(--c-text)]">Repository is empty</p>
          <p className="text-xs text-[var(--c-muted)]">Push at least one commit before opening a pull request.</p>
        </div>
      ) : branchOptions.length < 2 ? (
        <div className="rounded-lg border border-[var(--c-border)] p-8 text-center space-y-2">
          <p className="text-sm font-medium text-[var(--c-text)]">Not enough branches</p>
          <p className="text-xs text-[var(--c-muted)]">You need at least two branches to open a pull request.</p>
          <Link to={`/repos/${owner}/${repoName}/branches`} className="text-xs text-[var(--c-brand)] hover:underline">
            View branches →
          </Link>
        </div>
      ) : (
        <form onSubmit={handleSubmit} className="space-y-5">
          {/* Branch selectors */}
          <div className="flex items-center gap-3 flex-wrap">
            <div className="flex-1 min-w-[160px]">
              <label className="block text-xs font-medium text-[var(--c-muted)] mb-1">Source branch</label>
              <select value={sourceBranch} onChange={e => setSourceBranch(e.target.value)} required
                className="w-full border border-[var(--c-border)] rounded px-3 py-2 text-sm bg-[var(--c-surface)] text-[var(--c-text)] focus:outline-none focus:border-[var(--c-brand-focus)]">
                <option value="">Select branch…</option>
                {branchOptions.filter(b => b !== targetBranch).map(b => (
                  <option key={b} value={b}>{b}</option>
                ))}
              </select>
            </div>

            <div className="flex items-center pt-5 text-[var(--c-muted)]">
              <svg width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" d="M13.5 4.5 21 12m0 0-7.5 7.5M21 12H3" />
              </svg>
            </div>

            <div className="flex-1 min-w-[160px]">
              <label className="block text-xs font-medium text-[var(--c-muted)] mb-1">Target branch</label>
              <select value={targetBranch} onChange={e => setTargetBranch(e.target.value)} required
                className="w-full border border-[var(--c-border)] rounded px-3 py-2 text-sm bg-[var(--c-surface)] text-[var(--c-text)] focus:outline-none focus:border-[var(--c-brand-focus)]">
                <option value="">Select branch…</option>
                {branchOptions.filter(b => b !== sourceBranch).map(b => (
                  <option key={b} value={b}>{b}</option>
                ))}
              </select>
            </div>
          </div>

          {/* Title */}
          <div>
            <label className="block text-xs font-medium text-[var(--c-muted)] mb-1">
              Title <span className="text-[var(--c-danger)]">*</span>
            </label>
            <input
              value={title}
              onChange={e => setTitle(e.target.value)}
              placeholder="Brief description of the change"
              maxLength={255}
              className="w-full border border-[var(--c-border)] rounded px-3 py-2 text-sm bg-[var(--c-surface)] text-[var(--c-text)] focus:outline-none focus:border-[var(--c-brand-focus)]"
            />
          </div>

          {/* Body */}
          <div>
            <label className="block text-xs font-medium text-[var(--c-muted)] mb-1">Description</label>
            <textarea
              value={body}
              onChange={e => setBody(e.target.value)}
              rows={10}
              placeholder="Describe what changed and why…"
              className="w-full border border-[var(--c-border)] rounded px-3 py-2.5 text-sm font-mono bg-[var(--c-surface)] text-[var(--c-text)] focus:outline-none focus:border-[var(--c-brand-focus)] resize-y"
            />
          </div>

          {error && (
            <p className="text-sm text-[var(--c-danger)] bg-[var(--c-danger)]/5 border border-[var(--c-danger)]/20 rounded px-3 py-2">
              {error}
            </p>
          )}

          <div className="flex items-center gap-3">
            <button type="submit" disabled={createPR.isPending}
              className="px-5 py-2 rounded bg-[var(--c-brand)] text-white text-sm font-medium hover:bg-[var(--c-brand-hover)] disabled:opacity-50">
              {createPR.isPending ? 'Opening…' : 'Open pull request'}
            </button>
            <Link to={`/repos/${owner}/${repoName}/pulls`}
              className="px-4 py-2 rounded border border-[var(--c-border)] text-sm text-[var(--c-text)] hover:bg-[var(--c-surface-muted)]">
              Cancel
            </Link>
          </div>
        </form>
      )}
    </div>
  )
}
