import {
  AlertCircle,
  ArrowLeft,
  Circle,
  CircleCheck,
  Lock,
  MessageSquare,
  Send,
} from 'lucide-react';
import { useState } from 'react';
import { Link, useParams } from 'react-router-dom';

import { useIssueComments } from '@/hooks/issue/useIssueComments';
import { useIssueDetail } from '@/hooks/issue/useIssueDetail';
import { cn, timeAgo } from '@/lib/utils';

export function IssueDetailPage() {
  const { workspaceName = '', issueNumber } = useParams();
  const number = Number(issueNumber);

  const { data: issue, isLoading, error } = useIssueDetail(workspaceName, number);
  const { data: comments } = useIssueComments(workspaceName, number);

  const [commentBody, setCommentBody] = useState('');

  if (isLoading) {
    return (
      <div className="flex items-center gap-2 p-8 text-[14px] text-muted-foreground">
        <span className="inline-block size-4 animate-spin rounded-full border-2 border-muted-foreground border-t-transparent" />
        Loading issue…
      </div>
    );
  }

  if (error || !issue) {
    return (
      <div className="flex flex-col items-center justify-center px-8 py-20 text-center">
        <div className="grid size-16 place-items-center rounded-2xl bg-muted/40">
          <AlertCircle className="size-7 text-muted-foreground/40" />
        </div>
        <h2 className="mt-5 text-lg font-semibold text-foreground">Issue not found</h2>
        <p className="mt-2 max-w-sm text-[13px] text-muted-foreground">
          This issue doesn't exist or you don't have permission to view it.
        </p>
        <Link
          to={`/${workspaceName}/issues`}
          className="mt-4 text-[13px] text-primary hover:underline"
        >
          Back to issues
        </Link>
      </div>
    );
  }

  const isOpen = issue.state === 'Open';

  return (
    <div className="px-6 pt-6 pb-10">
      <Link
        to={`/${workspaceName}/issues`}
        className="mb-4 inline-flex items-center gap-1.5 text-[13px] text-muted-foreground hover:text-foreground transition-colors"
      >
        <ArrowLeft className="size-3.5" />
        Back to issues
      </Link>

      <div className="mb-6">
        <div className="flex items-start gap-3">
          <div className="mt-1 shrink-0">
            {isOpen ? (
              <Circle className="size-6 text-green-500" />
            ) : (
              <CircleCheck className="size-6 text-purple-500" />
            )}
          </div>
          <div className="min-w-0 flex-1">
            <h1 className="text-xl font-semibold text-foreground">
              {issue.title}
              <span className="ml-2 text-[14px] font-normal text-muted-foreground">
                #{issue.number}
              </span>
            </h1>
            <div className="mt-2 flex items-center gap-3 text-[13px] text-muted-foreground">
              <span
                className={cn(
                  'inline-flex items-center gap-1.5 rounded-full px-2.5 py-0.5 text-[12px] font-medium',
                  isOpen ? 'bg-green-500/10 text-green-600' : 'bg-purple-500/10 text-purple-600',
                )}
              >
                {isOpen ? 'Open' : 'Closed'}
              </span>
              <span>
                {issue.author.display_name ?? issue.author.username} opened{' '}
                {timeAgo(issue.created_at)}
              </span>
              {issue.priority && issue.priority !== 'None' && (
                <PriorityBadge priority={issue.priority} />
              )}
              {issue.locked && (
                <span className="inline-flex items-center gap-1 text-[12px] text-muted-foreground">
                  <Lock className="size-3" />
                  Locked
                </span>
              )}
            </div>
          </div>
        </div>
      </div>

      {issue.body && (
        <div className="mb-8 rounded-xl border border-border bg-card p-5">
          <div className="prose prose-sm max-w-none text-[14px] text-foreground whitespace-pre-wrap">
            {issue.body}
          </div>
        </div>
      )}

      <div className="mb-6 flex items-center gap-2 border-b border-border pb-3">
        <MessageSquare className="size-4 text-muted-foreground" />
        <h2 className="text-[14px] font-semibold text-foreground">
          Comments
          {(comments?.length ?? 0) > 0 && (
            <span className="ml-1.5 text-muted-foreground">({comments?.length})</span>
          )}
        </h2>
      </div>

      <div className="space-y-4">
        {comments?.map((comment) => (
          <div key={comment.id} className="rounded-xl border border-border bg-card p-4">
            <div className="mb-3 flex items-center gap-2">
              <div className="flex size-7 items-center justify-center rounded-full bg-muted text-[11px] font-semibold text-muted-foreground">
                {(comment.author.display_name ?? comment.author.username).slice(0, 2).toUpperCase()}
              </div>
              <span className="text-[13px] font-medium text-foreground">
                {comment.author.display_name ?? comment.author.username}
              </span>
              <span className="text-[12px] text-muted-foreground">
                {timeAgo(comment.created_at)}
              </span>
              {comment.updated_at !== comment.created_at && (
                <span className="text-[11px] text-muted-foreground italic">edited</span>
              )}
            </div>
            <div className="text-[14px] text-foreground whitespace-pre-wrap">{comment.body}</div>
          </div>
        ))}

        {(!comments || comments.length === 0) && (
          <div className="py-8 text-center text-[13px] text-muted-foreground">No comments yet</div>
        )}
      </div>

      <div className="mt-6 rounded-xl border border-border bg-card p-4">
        <textarea
          placeholder="Leave a comment..."
          value={commentBody}
          onChange={(e) => setCommentBody(e.target.value)}
          rows={4}
          className="w-full resize-none 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"
        />
        <div className="mt-3 flex items-center justify-between">
          <p className="text-[12px] text-muted-foreground">Markdown is supported</p>
          <button
            type="button"
            disabled={!commentBody.trim()}
            className="inline-flex items-center gap-1.5 rounded-md bg-primary px-3 py-[5px] text-[13px] font-medium text-primary-foreground transition-colors hover:bg-primary/85 disabled:opacity-50"
          >
            <Send className="size-3.5" />
            Comment
          </button>
        </div>
      </div>

      <div className="mt-6 flex items-center gap-3">
        {isOpen ? (
          <button
            type="button"
            className="inline-flex items-center gap-1.5 rounded-md border border-border px-3 py-[5px] text-[13px] font-medium text-foreground transition-colors hover:bg-muted"
          >
            <CircleCheck className="size-3.5 text-purple-500" />
            Close issue
          </button>
        ) : (
          <button
            type="button"
            className="inline-flex items-center gap-1.5 rounded-md border border-border px-3 py-[5px] text-[13px] font-medium text-foreground transition-colors hover:bg-muted"
          >
            <Circle className="size-3.5 text-green-500" />
            Reopen issue
          </button>
        )}
      </div>
    </div>
  );
}

function PriorityBadge({ priority }: { priority: string }) {
  return (
    <span
      className={cn(
        'inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-medium capitalize',
        priority === 'Critical'
          ? 'bg-destructive/10 text-destructive'
          : priority === 'High'
            ? 'bg-amber-500/10 text-amber-600'
            : priority === 'Medium'
              ? 'bg-blue-500/10 text-blue-600'
              : 'bg-muted text-muted-foreground',
      )}
    >
      {priority}
    </span>
  );
}
