import { BookOpen, Clock, FileText, Plus, Search } from 'lucide-react';
import { useState } from 'react';
import { Link, useParams } from 'react-router-dom';
import { Spinner } from '@/components/ui/spinner';
import { useCreateWikiPage } from '@/hooks/wiki/useCreateWikiPage';
import { useWikiPages } from '@/hooks/wiki/useWikiPages';
import { timeAgo } from '@/lib/utils';

export function RepoWikiPage() {
  const { workspaceName = '', repoName = '' } = useParams();
  const [search, setSearch] = useState('');
  const [showCreate, setShowCreate] = useState(false);
  const [newTitle, setNewTitle] = useState('');
  const [newContent, setNewContent] = useState('');

  const { data: pages, isLoading } = useWikiPages(workspaceName, repoName, search || null);
  const createPage = useCreateWikiPage(workspaceName, repoName);

  const list = pages ?? [];

  const handleCreate = () => {
    if (!newTitle.trim()) return;
    createPage.mutate(
      { title: newTitle.trim(), content: newContent.trim() },
      {
        onSuccess: () => {
          setNewTitle('');
          setNewContent('');
          setShowCreate(false);
        },
      },
    );
  };

  return (
    <div>
      <div className="mb-4 flex items-center justify-between">
        <div className="relative flex-1 max-w-sm">
          <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 size-3.5 text-muted-foreground" />
          <input
            type="text"
            placeholder="Search wiki pages..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="w-full rounded-lg border border-border bg-card pl-8 pr-3 py-[5px] text-[13px] text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring"
          />
        </div>
        <button
          type="button"
          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"
          onClick={() => setShowCreate(!showCreate)}
        >
          <Plus className="size-3.5" />
          New page
        </button>
      </div>

      {showCreate && (
        <div className="mb-4 space-y-3 rounded-lg border border-border p-4">
          <input
            type="text"
            placeholder="Page title"
            value={newTitle}
            onChange={(e) => setNewTitle(e.target.value)}
            className="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"
          />
          <textarea
            placeholder="Page content..."
            value={newContent}
            onChange={(e) => setNewContent(e.target.value)}
            rows={6}
            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="flex gap-2">
            <button
              type="button"
              disabled={!newTitle.trim() || createPage.isPending}
              onClick={handleCreate}
              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"
            >
              {createPage.isPending ? 'Creating...' : 'Create page'}
            </button>
            <button
              type="button"
              onClick={() => setShowCreate(false)}
              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"
            >
              Cancel
            </button>
          </div>
        </div>
      )}

      {isLoading ? (
        <div className="flex items-center gap-2 py-12 text-[14px] text-muted-foreground">
          <Spinner />
        </div>
      ) : list.length === 0 ? (
        <div className="flex flex-col items-center justify-center rounded-xl border border-dashed border-border py-16 text-center">
          <BookOpen className="size-8 text-muted-foreground/40" />
          <p className="mt-3 text-[14px] text-muted-foreground">
            {search ? 'No pages match your search' : 'No wiki pages yet'}
          </p>
          {!search && (
            <>
              <p className="mt-1 text-[13px] text-muted-foreground">
                Create the first page to get started
              </p>
              <button
                type="button"
                className="mt-3 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"
                onClick={() => setShowCreate(true)}
              >
                <Plus className="size-3.5" />
                Create first page
              </button>
            </>
          )}
        </div>
      ) : (
        <div className="overflow-hidden rounded-xl border border-border">
          {list.map((page) => (
            <Link
              key={page.id}
              to={`/${workspaceName}/repos/${repoName}/wiki/${page.slug}`}
              className="flex items-start gap-3 px-4 py-3 border-b border-border last:border-b-0 hover:bg-muted/50 transition-colors"
            >
              <div className="mt-0.5 shrink-0">
                <FileText className="size-5 text-muted-foreground" />
              </div>
              <div className="min-w-0 flex-1">
                <p className="text-[14px] font-medium text-foreground">{page.title}</p>
                {page.content && (
                  <p className="mt-0.5 truncate text-[12px] text-muted-foreground max-w-xl">
                    {page.content.slice(0, 120)}
                  </p>
                )}
                <div className="mt-1 flex items-center gap-3 text-[11px] text-muted-foreground">
                  <span className="flex items-center gap-1">
                    <Clock className="size-3" />
                    Updated {timeAgo(page.updated_at)}
                  </span>
                  <span>v{page.version}</span>
                </div>
              </div>
            </Link>
          ))}
        </div>
      )}
    </div>
  );
}
