'use client';

/**
 * Renders a rich preview card for detected URLs.
 * Supports: Issue, PR, Commit, Repository, External.
 */

import { useNavigate } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import {
  ExternalLink,
  GitPullRequest,
  GitCommit,
  BookOpen,
  AlertCircle,
  CheckCircle2,
  XCircle,
  GitMerge,
  ArrowUpRight,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import type { UnfurlResult } from '@/lib/link-unfurl';

interface LinkPreviewProps {
  result: UnfurlResult;
  /** Called when the preview is clicked */
  onClick?: (result: UnfurlResult) => void;
  className?: string;
}

// ── Issue Preview ─────────────────────────────────────────────────────────────

function IssuePreview({ result }: { result: UnfurlResult }) {
  const navigate = useNavigate();
  const { issueNumber, project } = result.ids;

  const { data: issue, isLoading } = useQuery({
    queryKey: ['issue-preview', project, issueNumber],
    queryFn: async () => {
      const { issueGet } = await import('@/client');
      const resp = await issueGet({ path: { project: project!, number: issueNumber! } });
      return resp.data?.data ?? null;
    },
    enabled: !!project && !!issueNumber,
    staleTime: 5 * 60 * 1000,
  });

  const isOpen = issue?.state === 'open';
  const Icon = isOpen ? AlertCircle : CheckCircle2;

  return (
    <button
      type="button"
      className="w-full text-left rounded-lg border bg-card overflow-hidden hover:border-primary/40 transition-colors"
      onClick={() => navigate(`/project/${project}/issues/${issueNumber}`)}
    >
      <div className="flex items-start gap-3 p-3">
        <div
          className={cn(
            'mt-0.5 flex-shrink-0 h-8 w-8 rounded-full border flex items-center justify-center',
            isOpen ? 'bg-emerald-500/10 border-emerald-500/20 text-emerald-600' : 'bg-violet-500/10 border-violet-500/20 text-violet-600',
          )}
        >
          <Icon className="h-4 w-4" />
        </div>
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-1.5 text-xs text-muted-foreground mb-0.5">
            <span className="font-mono text-xs">#{issueNumber}</span>
            {project && <span>in {project}</span>}
          </div>
          {isLoading ? (
            <div className="space-y-1.5">
              <div className="h-4 w-3/4 bg-muted rounded animate-pulse" />
              <div className="h-3 w-1/4 bg-muted rounded animate-pulse" />
            </div>
          ) : issue ? (
            <>
              <p className="text-sm font-medium text-foreground leading-tight truncate">
                {issue.title}
              </p>
              <div className="flex items-center gap-2 mt-1">
                <span
                  className={cn(
                    'text-xs px-1.5 py-0.5 rounded font-medium border',
                    isOpen
                      ? 'bg-emerald-50 text-emerald-700 border-emerald-200 dark:bg-emerald-950/40 dark:text-emerald-400 dark:border-emerald-800'
                      : 'bg-violet-50 text-violet-700 border-violet-200 dark:bg-violet-950/40 dark:text-violet-400 dark:border-violet-800',
                  )}
                >
                  {isOpen ? 'Open' : 'Closed'}
                </span>
                <span className="text-xs text-muted-foreground">
                  by {issue.author_username ?? issue.author}
                </span>
              </div>
            </>
          ) : (
            <p className="text-xs text-muted-foreground italic">Issue not found</p>
          )}
        </div>
        <ArrowUpRight className="h-4 w-4 text-muted-foreground flex-shrink-0 mt-0.5" />
      </div>
    </button>
  );
}

// ── PR Preview ─────────────────────────────────────────────────────────────

function PRPreview({ result }: { result: UnfurlResult }) {
  const navigate = useNavigate();
  const { prNumber, namespace, repo } = result.ids;

  const { data: pr, isLoading } = useQuery({
    queryKey: ['pr-preview', namespace, repo, prNumber],
    queryFn: async () => {
      const { pullRequestGet } = await import('@/client');
      const resp = await pullRequestGet({ path: { namespace: namespace!, repo: repo!, number: prNumber! } });
      return resp.data?.data ?? null;
    },
    enabled: !!namespace && !!repo && !!prNumber,
    staleTime: 5 * 60 * 1000,
  });

  const status = pr?.status ?? 'open';
  const StatusIcon =
    status === 'merged' ? GitMerge : status === 'closed' ? XCircle : GitPullRequest;

  return (
    <button
      type="button"
      className="w-full text-left rounded-lg border bg-card overflow-hidden hover:border-primary/40 transition-colors"
      onClick={() => navigate(`/repository/${namespace}/${repo}/pulls/${prNumber}`)}
    >
      <div className="flex items-start gap-3 p-3">
        <div
          className={cn(
            'mt-0.5 flex-shrink-0 h-8 w-8 rounded-full border flex items-center justify-center',
            status === 'open'
              ? 'bg-emerald-500/10 border-emerald-500/20 text-emerald-600'
              : status === 'merged'
              ? 'bg-purple-500/10 border-purple-500/20 text-purple-600'
              : 'bg-red-500/10 border-red-500/20 text-red-600',
          )}
        >
          <StatusIcon className="h-4 w-4" />
        </div>
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-1.5 text-xs text-muted-foreground mb-0.5">
            <span className="font-mono text-xs">#{prNumber}</span>
            {namespace && repo && <span>in {namespace}/{repo}</span>}
          </div>
          {isLoading ? (
            <div className="space-y-1.5">
              <div className="h-4 w-3/4 bg-muted rounded animate-pulse" />
              <div className="h-3 w-1/3 bg-muted rounded animate-pulse" />
            </div>
          ) : pr ? (
            <>
              <p className="text-sm font-medium text-foreground leading-tight truncate">
                {pr.title}
              </p>
              <div className="flex items-center gap-2 mt-1">
                <span
                  className={cn(
                    'text-xs px-1.5 py-0.5 rounded font-medium border capitalize',
                    status === 'open'
                      ? 'bg-emerald-50 text-emerald-700 border-emerald-200'
                      : status === 'merged'
                      ? 'bg-purple-50 text-purple-700 border-purple-200'
                      : 'bg-red-50 text-red-700 border-red-200',
                  )}
                >
                  {status}
                </span>
                <span className="text-xs text-muted-foreground">
                  {pr.author_username ?? pr.author}
                </span>
              </div>
            </>
          ) : (
            <p className="text-xs text-muted-foreground italic">PR not found</p>
          )}
        </div>
        <ArrowUpRight className="h-4 w-4 text-muted-foreground flex-shrink-0 mt-0.5" />
      </div>
    </button>
  );
}

// ── Commit Preview ─────────────────────────────────────────────────────────

function CommitPreview({ result }: { result: UnfurlResult }) {
  const navigate = useNavigate();
  const { commitOid, namespace, repo } = result.ids;
  const shortOid = commitOid?.slice(0, 7) ?? 'unknown';

  return (
    <button
      type="button"
      className="w-full text-left rounded-lg border bg-card overflow-hidden hover:border-primary/40 transition-colors"
      onClick={() => navigate(`/repository/${namespace}/${repo}/commit/${commitOid}`)}
    >
      <div className="flex items-start gap-3 p-3">
        <div className="mt-0.5 flex-shrink-0 h-8 w-8 rounded-full border bg-muted flex items-center justify-center text-muted-foreground">
          <GitCommit className="h-4 w-4" />
        </div>
        <div className="flex-1 min-w-0">
          <div className="text-xs text-muted-foreground mb-0.5">
            {namespace}/{repo}
          </div>
          <p className="text-sm font-mono text-foreground">
            {shortOid}
          </p>
        </div>
        <ArrowUpRight className="h-4 w-4 text-muted-foreground flex-shrink-0 mt-0.5" />
      </div>
    </button>
  );
}

// ── Repository Preview ─────────────────────────────────────────────────────

function RepoPreview({ result }: { result: UnfurlResult }) {
  const navigate = useNavigate();
  const { namespace, repo } = result.ids;

  return (
    <button
      type="button"
      className="w-full text-left rounded-lg border bg-card overflow-hidden hover:border-primary/40 transition-colors"
      onClick={() => navigate(`/repository/${namespace}/${repo}`)}
    >
      <div className="flex items-start gap-3 p-3">
        <div className="mt-0.5 flex-shrink-0 h-8 w-8 rounded-full border bg-muted flex items-center justify-center text-muted-foreground">
          <BookOpen className="h-4 w-4" />
        </div>
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-1.5 text-xs text-muted-foreground mb-0.5">
            <span className="font-medium text-foreground">
              {namespace}/{repo}
            </span>
          </div>
          <p className="text-xs text-muted-foreground">Repository</p>
        </div>
        <ArrowUpRight className="h-4 w-4 text-muted-foreground flex-shrink-0 mt-0.5" />
      </div>
    </button>
  );
}

// ── External URL Preview ────────────────────────────────────────────────────

function ExternalPreview({ result }: { result: UnfurlResult }) {
  return (
    <a
      href={result.url}
      target="_blank"
      rel="noopener noreferrer"
      className="w-full flex items-start gap-3 p-3 rounded-lg border bg-card overflow-hidden hover:border-primary/40 transition-colors"
    >
      <div className="mt-0.5 flex-shrink-0 h-8 w-8 rounded-full border bg-muted flex items-center justify-center text-muted-foreground">
        <ExternalLink className="h-4 w-4" />
      </div>
      <div className="flex-1 min-w-0">
        <p className="text-xs font-medium text-foreground truncate">{result.domain}</p>
        <p className="text-xs text-muted-foreground truncate">{result.url}</p>
      </div>
      <ExternalLink className="h-3.5 w-3.5 text-muted-foreground flex-shrink-0 mt-0.5" />
    </a>
  );
}

// ── Main LinkPreview component ───────────────────────────────────────────────

export function LinkPreview({ result, className }: LinkPreviewProps) {
  switch (result.type) {
    case 'issue':
      return <IssuePreview result={result} />;
    case 'pull_request':
      return <PRPreview result={result} />;
    case 'commit':
      return <CommitPreview result={result} />;
    case 'repository':
      return <RepoPreview result={result} />;
    case 'external':
      return <ExternalPreview result={result} />;
    default:
      // Fallback: render as a simple link
      return (
        <a
          href={result.url}
          target="_blank"
          rel="noopener noreferrer"
          className={cn(
            'text-primary underline underline-offset-2 text-sm',
            className,
          )}
        >
          {result.url}
        </a>
      );
  }
}
