import { ArrowLeft, BookOpen, Clock, FileText, History, Pencil, Save, Trash2, X } from 'lucide-react';
import { useState } from 'react';
import { Link, useNavigate, useParams } from 'react-router-dom';

import { Spinner } from '@/components/ui/spinner';
import { useDeleteWikiPage } from '@/hooks/wiki/useDeleteWikiPage';
import { useUpdateWikiPage } from '@/hooks/wiki/useUpdateWikiPage';
import { useWikiPage } from '@/hooks/wiki/useWikiPage';
import { useWikiRevisions } from '@/hooks/wiki/useWikiRevisions';
import { cn, timeAgo } from '@/lib/utils';

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

  const { data: page, isLoading, error } = useWikiPage(workspaceName, repoName, slug ?? null);
  const { data: revisions } = useWikiRevisions(workspaceName, repoName, slug ?? null);
  const updatePage = useUpdateWikiPage(workspaceName, repoName);
  const deletePage = useDeleteWikiPage(workspaceName, repoName);

  const [activeTab, setActiveTab] = useState<'content' | 'history'>('content');
  const [isEditing, setIsEditing] = useState(false);
  const [editTitle, setEditTitle] = useState('');
  const [editContent, setEditContent] = useState('');

  if (isLoading) {
    return (
      <div className="flex items-center gap-2 p-8 text-[14px] text-muted-foreground">
        <Spinner />
        Loading wiki page…
      </div>
    );
  }

  if (error || !page) {
    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">
          <BookOpen className="size-7 text-muted-foreground/40" />
        </div>
        <h2 className="mt-5 text-lg font-semibold text-foreground">Page not found</h2>
        <p className="mt-2 max-w-sm text-[13px] text-muted-foreground">
          This wiki page doesn't exist or you don't have permission to view it.
        </p>
        <Link
          to={`/${workspaceName}/repos/${repoName}/wiki`}
          className="mt-4 text-[13px] text-primary hover:underline"
        >
          Back to wiki
        </Link>
      </div>
    );
  }

  const startEditing = () => {
    setEditTitle(page.title);
    setEditContent(page.content);
    setIsEditing(true);
  };

  const cancelEditing = () => {
    setIsEditing(false);
    setEditTitle('');
    setEditContent('');
  };

  const saveEdit = () => {
    if (!editTitle.trim() || !slug) return;
    updatePage.mutate(
      {
        slug,
        title: editTitle.trim(),
        content: editContent.trim(),
      },
      { onSuccess: () => setIsEditing(false) },
    );
  };

  const handleDelete = () => {
    if (!slug) return;
    if (confirm(`Delete wiki page "${page.title}"?`)) {
      deletePage.mutate(slug, {
        onSuccess: () => navigate(`/${workspaceName}/repos/${repoName}/wiki`),
      });
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <Link
          to={`/${workspaceName}/repos/${repoName}/wiki`}
          className="inline-flex items-center gap-1.5 text-[13px] text-muted-foreground hover:text-foreground transition-colors"
        >
          <ArrowLeft className="size-3.5" />
          Back to wiki
        </Link>
        <div className="flex items-center gap-2">
          {!isEditing && (
            <>
              <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"
                onClick={startEditing}
              >
                <Pencil className="size-3.5" />
                Edit
              </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-destructive transition-colors hover:bg-destructive/10"
                onClick={handleDelete}
                disabled={deletePage.isPending}
              >
                <Trash2 className="size-3.5" />
                Delete
              </button>
            </>
          )}
        </div>
      </div>

      {isEditing ? (
        <div className="space-y-3">
          <input
            type="text"
            value={editTitle}
            onChange={(e) => setEditTitle(e.target.value)}
            className="w-full rounded-lg border border-border bg-background px-3 py-2 text-[16px] font-semibold text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring"
          />
          <textarea
            value={editContent}
            onChange={(e) => setEditContent(e.target.value)}
            rows={20}
            className="w-full resize-y rounded-lg border border-border bg-background px-3 py-2 text-[14px] font-mono text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring"
          />
          <div className="flex items-center gap-2">
            <button
              type="button"
              disabled={!editTitle.trim() || updatePage.isPending}
              onClick={saveEdit}
              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"
            >
              <Save className="size-3.5" />
              {updatePage.isPending ? 'Saving...' : 'Save changes'}
            </button>
            <button
              type="button"
              onClick={cancelEditing}
              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"
            >
              <X className="size-3.5" />
              Cancel
            </button>
          </div>
        </div>
      ) : (
        <>
          <div>
            <h1 className="text-xl font-semibold text-foreground">{page.title}</h1>
            <div className="mt-2 flex items-center gap-3 text-[12px] text-muted-foreground">
              <span className="flex items-center gap-1">
                <Clock className="size-3" />
                Updated {timeAgo(page.updated_at)}
              </span>
              <span>Version {page.version}</span>
            </div>
          </div>

          <div className="flex items-center gap-1 border-b border-border">
            <button
              type="button"
              onClick={() => setActiveTab('content')}
              className={cn(
                'flex items-center gap-1.5 border-b-2 px-4 py-2.5 text-[13px] font-medium transition-colors',
                activeTab === 'content'
                  ? 'border-primary text-foreground'
                  : 'border-transparent text-muted-foreground hover:text-foreground',
              )}
            >
              <FileText className="size-3.5" />
              Content
            </button>
            <button
              type="button"
              onClick={() => setActiveTab('history')}
              className={cn(
                'flex items-center gap-1.5 border-b-2 px-4 py-2.5 text-[13px] font-medium transition-colors',
                activeTab === 'history'
                  ? 'border-primary text-foreground'
                  : 'border-transparent text-muted-foreground hover:text-foreground',
              )}
            >
              <History className="size-3.5" />
              History
              {revisions && revisions.length > 0 && (
                <span className="ml-1 rounded-full bg-muted px-2 py-0.5 text-[11px]">
                  {revisions.length}
                </span>
              )}
            </button>
          </div>

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

          {activeTab === 'history' && (
            <div className="space-y-3">
              {revisions && revisions.length > 0 ? (
                revisions.map((revision) => (
                  <div
                    key={revision.id}
                    className="flex items-start gap-3 rounded-xl border border-border bg-card px-4 py-3"
                  >
                    <History className="mt-0.5 size-4 shrink-0 text-muted-foreground" />
                    <div className="min-w-0 flex-1">
                      <div className="flex items-center gap-2">
                        <span className="text-[13px] font-medium text-foreground">
                          Version {revision.version}
                        </span>
                        <span className="text-[12px] text-muted-foreground">
                          {timeAgo(revision.created_at)}
                        </span>
                      </div>
                      {revision.commit_message && (
                        <p className="mt-0.5 text-[12px] text-muted-foreground">
                          {revision.commit_message}
                        </p>
                      )}
                    </div>
                  </div>
                ))
              ) : (
                <div className="py-8 text-center text-[13px] text-muted-foreground">
                  No revision history available
                </div>
              )}
            </div>
          )}
        </>
      )}
    </div>
  );
}
