import { useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { ArrowLeft, GitPullRequest } from 'lucide-react';

import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { useCreatePr } from '@/hooks/pull-request/useCreatePr';
import { useRepo } from '@/hooks/repo/useRepo';
import { useRepoBranches } from '@/hooks/repo/useRepoBranches';

export function RepoCreatePrPage() {
  const { workspaceName = '', repoName = '' } = useParams();
  const navigate = useNavigate();

  const { data: repo } = useRepo(workspaceName, repoName);
  const { data: branches } = useRepoBranches(workspaceName, repoName);
  const createPr = useCreatePr(workspaceName, repoName);

  const [title, setTitle] = useState('');
  const [body, setBody] = useState('');
  const [sourceBranch, setSourceBranch] = useState('');
  const [targetBranch, setTargetBranch] = useState(repo?.default_branch || '');
  const [draft, setDraft] = useState(false);

  const branchNames = (branches ?? []).map((b: { name: string }) => b.name);

  const handleSubmit = () => {
    if (!title.trim() || !sourceBranch || !targetBranch) return;
    createPr.mutate(
      {
        title: title.trim(),
        body: body.trim() || undefined,
        source_branch: sourceBranch,
        target_branch: targetBranch,
        source_repo_id: repo?.id || '',
        head_commit_sha: '',
        draft,
      },
      {
        onSuccess: () => {
          navigate(`/${workspaceName}/repos/${repoName}/pulls`);
        },
      },
    );
  };

  return (
    <div className="mx-auto max-w-2xl space-y-6">
      <div className="flex items-center gap-2">
        <button
          type="button"
          className="flex items-center gap-1 text-[13px] text-muted-foreground hover:text-foreground"
          onClick={() => navigate(`/${workspaceName}/repos/${repoName}/pulls`)}
        >
          <ArrowLeft className="size-3.5" />
          Back to pull requests
        </button>
      </div>

      <div>
        <div className="flex items-center gap-2">
          <GitPullRequest className="size-5 text-green-500" />
          <h1 className="text-lg font-semibold text-foreground">Create pull request</h1>
        </div>
      </div>

      <div className="space-y-5">
        <div className="flex items-center gap-3 rounded-xl border border-border bg-card p-4">
          <select
            className="h-9 rounded-lg border border-border bg-transparent px-3 text-[13px] text-foreground"
            value={sourceBranch}
            onChange={(e) => setSourceBranch(e.target.value)}
          >
            <option value="">Select source branch</option>
            {branchNames.map((name: string) => (
              <option key={name} value={name}>
                {name}
              </option>
            ))}
          </select>
          <span className="text-muted-foreground">→</span>
          <select
            className="h-9 rounded-lg border border-border bg-transparent px-3 text-[13px] text-foreground"
            value={targetBranch}
            onChange={(e) => setTargetBranch(e.target.value)}
          >
            <option value="">Select target branch</option>
            {branchNames.map((name: string) => (
              <option key={name} value={name}>
                {name}
              </option>
            ))}
          </select>
        </div>

        <div>
          <label htmlFor="pr-title" className="text-[13px] font-medium text-foreground">
            Title
          </label>
          <Input
            id="pr-title"
            className="mt-1 h-10 text-[14px]"
            placeholder="Pull request title"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
          />
        </div>

        <div>
          <label htmlFor="pr-body" className="text-[13px] font-medium text-foreground">
            Description <span className="text-muted-foreground">(optional)</span>
          </label>
          <textarea
            id="pr-body"
            className="mt-1 w-full rounded-lg border border-border bg-background px-3 py-2 text-[14px] text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring"
            rows={8}
            placeholder="Describe your changes..."
            value={body}
            onChange={(e) => setBody(e.target.value)}
          />
        </div>

        <label className="flex items-center gap-2 text-[13px]">
          <input
            type="checkbox"
            checked={draft}
            onChange={(e) => setDraft(e.target.checked)}
            className="rounded border-border"
          />
          Create as draft
        </label>

        <div className="flex items-center gap-3">
          <Button
            disabled={
              !title.trim() ||
              !sourceBranch ||
              !targetBranch ||
              sourceBranch === targetBranch ||
              createPr.isPending
            }
            onClick={handleSubmit}
          >
            {createPr.isPending ? 'Creating...' : 'Create pull request'}
          </Button>
          <Button
            variant="outline"
            onClick={() => navigate(`/${workspaceName}/repos/${repoName}/pulls`)}
          >
            Cancel
          </Button>
        </div>

        {sourceBranch === targetBranch && sourceBranch && (
          <p className="text-[12px] text-amber-600">
            Source and target branches must be different
          </p>
        )}
      </div>
    </div>
  );
}
