import { useState } from 'react';
import { Link, useParams, useSearchParams } from 'react-router-dom';
import { Clock, GitCommit, Hash, Search } from 'lucide-react';

import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Spinner } from '@/components/ui/spinner';
import { useGitCommits } from '@/hooks/repo/useGitCommits';
import { useRepo } from '@/hooks/repo/useRepo';
import { useRepoBranches } from '@/hooks/repo/useRepoBranches';
import { timeAgo } from '@/lib/utils';

export function RepoCommitsPage() {
  const { workspaceName = '', repoName = '' } = useParams();
  const [searchParams, setSearchParams] = useSearchParams();
  const [search, setSearch] = useState('');
  const [showBranchSelector, setShowBranchSelector] = useState(false);

  const branch = searchParams.get('branch') || '';
  const { data: repo } = useRepo(workspaceName, repoName);
  const { data: branches } = useRepoBranches(workspaceName, repoName);
  const { data: commitsData, isLoading } = useGitCommits(
    workspaceName,
    repoName,
    branch || repo?.default_branch,
  );

  const effectiveBranch = branch || repo?.default_branch || '';
  const commits = commitsData?.commits ?? [];
  const filtered = search
    ? commits.filter(
        (c) =>
          c.subject.toLowerCase().includes(search.toLowerCase()) ||
          c.abbreviated_oid.includes(search),
      )
    : commits;

  return (
    <div className="space-y-4">
      <div className="flex items-center gap-2">
        <div className="relative">
          <Button
            variant="outline"
            size="sm"
            onClick={() => setShowBranchSelector(!showBranchSelector)}
          >
            {effectiveBranch || 'Select branch'}
          </Button>
          {showBranchSelector && (
            <div className="absolute top-full left-0 z-10 mt-1 w-48 rounded-lg border border-border bg-card shadow-lg">
              <div className="max-h-64 overflow-y-auto p-1">
                {branches?.map((b: { name: string; id?: string }) => (
                  <button
                    key={b.id || b.name}
                    type="button"
                    className={`w-full rounded px-3 py-1.5 text-left text-[13px] transition-colors ${
                      b.name === effectiveBranch
                        ? 'bg-primary/10 text-primary'
                        : 'text-foreground hover:bg-muted'
                    }`}
                    onClick={() => {
                      setSearchParams({ branch: b.name }, { replace: true });
                      setShowBranchSelector(false);
                    }}
                  >
                    {b.name}
                  </button>
                ))}
              </div>
            </div>
          )}
        </div>
        <div className="relative ml-auto max-w-[300px]">
          <Search className="absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground" />
          <Input
            className="h-8 pl-8 text-[13px]"
            placeholder="Search commits..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
          />
        </div>
      </div>

      <div className="overflow-hidden rounded-lg border border-border">
        {isLoading ? (
          <div className="flex items-center justify-center py-12">
            <Spinner />
          </div>
        ) : filtered.length > 0 ? (
          <div className="divide-y divide-border">
            {filtered.map((commit) => (
              <Link
                key={commit.abbreviated_oid}
                to={`/${workspaceName}/repos/${repoName}/commits/${commit.abbreviated_oid}`}
                className="flex items-center gap-3 px-4 py-3 transition-colors hover:bg-muted/40"
              >
                <GitCommit className="size-4 shrink-0 text-muted-foreground" />
                <div className="min-w-0 flex-1">
                  <p className="truncate text-[13px] font-medium text-foreground">
                    {commit.subject}
                  </p>
                  <div className="mt-0.5 flex items-center gap-2 text-[11px] text-muted-foreground">
                    <span>{commit.author?.identity?.name || 'Unknown'}</span>
                    {commit.authored_at && (
                      <span className="flex items-center gap-0.5">
                        <Clock className="size-2.5" />
                        {timeAgo(
                          new Date(
                            commit.authored_at.seconds * 1000,
                          ).toISOString(),
                        )}
                      </span>
                    )}
                  </div>
                </div>
                <code className="flex items-center gap-1 text-[11px] text-muted-foreground/60">
                  <Hash className="size-2.5" />
                  {commit.abbreviated_oid}
                </code>
              </Link>
            ))}
          </div>
        ) : (
          <div className="py-12 text-center">
            <GitCommit className="mx-auto size-5 text-muted-foreground/20" />
            <p className="mt-3 text-[13px] text-muted-foreground">
              {search ? `No commits matching "${search}"` : 'No commits yet'}
            </p>
          </div>
        )}
      </div>
    </div>
  );
}
