import { ArrowUpDown, ChevronDown, ExternalLink, Search } from 'lucide-react';

import { Fragment, useEffect, useState, useRef } from 'react';

import { Head, Link, router } from '@inertiajs/react';

import QualityScoresCard from '@/Components/Content/QualityScoresCard';
import SiteNav from '@/Components/Navigation/SiteNav';
import InertiaPagination from '@/Components/Shared/InertiaPagination';
import { Button } from '@/Components/ui/button';
import { Card, CardContent } from '@/Components/ui/card';
import { EmptyState } from '@/Components/ui/empty-state';
import { Input } from '@/Components/ui/input';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/Components/ui/table';
import { useNavigationState } from '@/hooks/useNavigationState';
import { useSiteKeyboardShortcuts } from '@/hooks/useSiteKeyboardShortcuts';
import DashboardLayout from '@/Layouts/DashboardLayout';
import { trackEvent, trackFilterApplied } from '@/lib/analytics';
import { CONTENT_INVENTORY_VIEWED } from '@/lib/event-catalog';
import { formatDate, formatNumber } from '@/lib/format';
import { cn } from '@/lib/utils';
import type { SiteBasic } from '@/types';

interface WpPost {
  id: number;
  wp_post_id: number;
  title: string;
  url: string;
  post_type: string;
  post_status: string;
  wp_modified_at: string | null;
  word_count: number | null;
  flesch_kincaid_grade: number | null;
  avg_sentence_length: number | null;
  paragraph_count: number | null;
  passive_voice_percentage: number | null;
  h1_count: number | null;
  h2_count: number | null;
  h3_count: number | null;
  h4_count: number | null;
  h5_count: number | null;
  h6_count: number | null;
  image_count: number | null;
  internal_link_count: number | null;
  external_link_count: number | null;
}

interface PaginatedPosts {
  data: WpPost[];
  links: Array<{ url: string | null; label: string; active: boolean }>;
  current_page: number;
  last_page: number;
}

interface Filters {
  post_type: string | null;
  post_status: string | null;
  search: string | null;
  sort_by: string;
  sort_direction: string;
}

interface Props {
  site: SiteBasic;
  posts: PaginatedPosts;
  filters: Filters;
  postTypeCounts: Record<string, number>;
  postStatusCounts: Record<string, number>;
  totalPosts: number;
  has_wp: boolean;
}

export default function ContentInventory({
  site,
  posts,
  filters,
  postTypeCounts,
  postStatusCounts,
  totalPosts,
  has_wp,
}: Props) {
  useEffect(() => {
    trackEvent(CONTENT_INVENTORY_VIEWED, { site_id: String(site.id) });
  }, [site.id]);

  const [searchInput, setSearchInput] = useState(filters.search ?? '');
  const [selectedPost, setSelectedPost] = useState<WpPost | null>(null);
  const [expandedRowId, setExpandedRowId] = useState<number | null>(null);
  const searchInputRef = useRef<HTMLInputElement>(null);
  const isNavigating = useNavigationState();

  const currentPage = posts.current_page;
  const lastPage = posts.last_page;

  const handleFilterChange = (key: string, value: string | null) => {
    if (value) {
      trackFilterApplied(key, value);
    }
    router.get(
      route('content-inventory.index', site.id),
      { ...filters, [key]: value },
      { preserveState: true, preserveScroll: true },
    );
  };

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    handleFilterChange('search', searchInput || null);
  };

  const handleSort = (field: string) => {
    const newDirection =
      filters.sort_by === field && filters.sort_direction === 'desc' ? 'asc' : 'desc';
    router.get(
      route('content-inventory.index', site.id),
      { ...filters, sort_by: field, sort_direction: newDirection },
      { preserveState: true, preserveScroll: true },
    );
  };

  const getSortIcon = (field: string) => {
    if (filters.sort_by !== field) {
      return <ArrowUpDown className="ml-1 h-4 w-4 inline opacity-0 group-hover:opacity-50" />;
    }
    return (
      <ArrowUpDown
        className={`ml-1 h-4 w-4 inline ${filters.sort_direction === 'asc' ? 'rotate-180' : ''}`}
      />
    );
  };

  const truncateTitle = (title: string, maxLength: number): string => {
    return title.length > maxLength ? title.slice(0, maxLength) + '...' : title;
  };

  const handlePage = (page: number) => {
    router.get(
      route('content-inventory.index', site.id),
      { ...filters, page },
      { preserveState: true, preserveScroll: true },
    );
  };

  const toggleRow = (postId: number) => {
    setExpandedRowId(expandedRowId === postId ? null : postId);
  };

  useSiteKeyboardShortcuts({
    onSearch: () => searchInputRef.current?.focus(),
    onNextPage: currentPage < lastPage ? () => handlePage(currentPage + 1) : undefined,
    onPrevPage: currentPage > 1 ? () => handlePage(currentPage - 1) : undefined,
  });
  return (
    <>
      <Head title={`${site.name} - Content Inventory`} />

      <div className="container py-6">
        <SiteNav
          siteId={site.id}
          canAnalyze
          canRecommend
          canCannibalization
          canOpportunityMap
          canGeographic
          canDevice
        />

        <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between mb-4">
          <h1 className="text-2xl font-bold tracking-tight">Content Inventory</h1>
        </div>

        {totalPosts === 0 ? (
          has_wp ? (
            <EmptyState
              title="No content yet"
              description="Your WordPress site is connected — content will appear after the next sync."
              action={
                <Button asChild>
                  <Link href={route('onboarding.index', site.id)}>Check sync status</Link>
                </Button>
              }
            />
          ) : (
            <EmptyState
              title="Connect WordPress"
              description="RankWiz needs WordPress access to score your content quality."
              action={
                <Button asChild>
                  <Link href={route('onboarding.index', site.id)}>Connect WordPress</Link>
                </Button>
              }
            />
          )
        ) : (
          <>
            {/* Filters */}
            <div className="mb-4 flex flex-col gap-3 sm:flex-row sm:items-center">
              {/* Search */}
              <form onSubmit={handleSearch} className="flex-1">
                <div className="relative">
                  <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                  <Input
                    ref={searchInputRef}
                    type="text"
                    placeholder="Search by title or URL..."
                    value={searchInput}
                    onChange={(e) => setSearchInput(e.target.value)}
                    className="pl-9"
                    disabled={isNavigating}
                  />
                </div>
              </form>

              {/* Post Type Filter */}
              <div className="flex flex-wrap gap-2">
                <Button
                  variant={filters.post_type === null ? 'default' : 'outline'}
                  size="sm"
                  onClick={() => handleFilterChange('post_type', null)}
                  disabled={isNavigating}
                >
                  All Types ({totalPosts})
                </Button>
                {Object.entries(postTypeCounts).map(([type, count]) => (
                  <Button
                    key={type}
                    variant={filters.post_type === type ? 'default' : 'outline'}
                    size="sm"
                    onClick={() => handleFilterChange('post_type', type)}
                    disabled={isNavigating}
                  >
                    {type} ({count})
                  </Button>
                ))}
              </div>

              {/* Post Status Filter */}
              <div className="flex flex-wrap gap-2">
                <Button
                  variant={filters.post_status === null ? 'default' : 'outline'}
                  size="sm"
                  onClick={() => handleFilterChange('post_status', null)}
                  disabled={isNavigating}
                >
                  All Statuses
                </Button>
                {Object.entries(postStatusCounts).map(([status, count]) => (
                  <Button
                    key={status}
                    variant={filters.post_status === status ? 'default' : 'outline'}
                    size="sm"
                    onClick={() => handleFilterChange('post_status', status)}
                    disabled={isNavigating}
                  >
                    {status} ({count})
                  </Button>
                ))}
              </div>
            </div>

            {posts.data.length === 0 ? (
              <EmptyState
                title="No posts match filters"
                description="Try adjusting your filters or search query."
              />
            ) : (
              <div className="space-y-4">
                {/* Posts Table */}
                <div className="rounded-lg border">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead className="w-8 lg:hidden"></TableHead>
                        <TableHead>
                          <button
                            className="group flex items-center hover:text-foreground rounded outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
                            onClick={() => handleSort('title')}
                            aria-label={`Sort by title${filters.sort_by === 'title' ? `, currently ${filters.sort_direction}ending` : ''}`}
                          >
                            Title
                            {getSortIcon('title')}
                          </button>
                        </TableHead>
                        <TableHead className="hidden md:table-cell">Type</TableHead>
                        <TableHead className="hidden md:table-cell">Status</TableHead>
                        <TableHead className="hidden lg:table-cell">
                          <button
                            className="group flex items-center hover:text-foreground rounded outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
                            onClick={() => handleSort('word_count')}
                            aria-label={`Sort by word count${filters.sort_by === 'word_count' ? `, currently ${filters.sort_direction}ending` : ''}`}
                          >
                            Words
                            {getSortIcon('word_count')}
                          </button>
                        </TableHead>
                        <TableHead className="hidden lg:table-cell">
                          <button
                            className="group flex items-center hover:text-foreground rounded outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
                            onClick={() => handleSort('flesch_kincaid_grade')}
                            aria-label={`Sort by reading level${filters.sort_by === 'flesch_kincaid_grade' ? `, currently ${filters.sort_direction}ending` : ''}`}
                          >
                            Reading Level
                            {getSortIcon('flesch_kincaid_grade')}
                          </button>
                        </TableHead>
                        <TableHead>
                          <button
                            className="group flex items-center hover:text-foreground rounded outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
                            onClick={() => handleSort('wp_modified_at')}
                            aria-label={`Sort by modified date${filters.sort_by === 'wp_modified_at' ? `, currently ${filters.sort_direction}ending` : ''}`}
                          >
                            Modified
                            {getSortIcon('wp_modified_at')}
                          </button>
                        </TableHead>
                        <TableHead className="text-right">Actions</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {posts.data.map((post) => {
                        const isExpanded = expandedRowId === post.id;
                        return (
                          <Fragment key={post.id}>
                            <TableRow
                              className={cn('group', isExpanded ? '' : 'border-b last:border-0')}
                            >
                              <TableCell className="lg:hidden">
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  className="h-6 w-6 p-0"
                                  onClick={() => toggleRow(post.id)}
                                  aria-label={isExpanded ? 'Collapse details' : 'Expand details'}
                                >
                                  <ChevronDown
                                    className={cn(
                                      'h-4 w-4 transition-transform duration-200',
                                      isExpanded && 'rotate-180',
                                    )}
                                  />
                                </Button>
                              </TableCell>
                              <TableCell>
                                <div className="flex flex-col gap-1">
                                  <button
                                    onClick={() => setSelectedPost(post)}
                                    className="text-left font-medium hover:underline"
                                    title={post.title}
                                  >
                                    {truncateTitle(post.title, 60)}
                                  </button>
                                  <a
                                    href={post.url}
                                    target="_blank"
                                    rel="noopener noreferrer"
                                    className="inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-primary hover:underline"
                                  >
                                    {truncateTitle(post.url, 50)}
                                    <ExternalLink className="h-3 w-3" />
                                  </a>
                                </div>
                              </TableCell>
                              <TableCell className="hidden md:table-cell">
                                <span className="rounded-full bg-muted px-2 py-1 text-xs">
                                  {post.post_type}
                                </span>
                              </TableCell>
                              <TableCell className="hidden md:table-cell">
                                <span className="rounded-full bg-muted px-2 py-1 text-xs">
                                  {post.post_status}
                                </span>
                              </TableCell>
                              <TableCell className="hidden lg:table-cell tabular-nums">
                                {post.word_count != null ? formatNumber(post.word_count) : 'N/A'}
                              </TableCell>
                              <TableCell className="hidden lg:table-cell tabular-nums">
                                {post.flesch_kincaid_grade !== null
                                  ? `Grade ${post.flesch_kincaid_grade.toFixed(1)}`
                                  : 'N/A'}
                              </TableCell>
                              <TableCell className="tabular-nums">
                                {post.wp_modified_at ? formatDate(post.wp_modified_at) : 'N/A'}
                              </TableCell>
                              <TableCell className="text-right">
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  onClick={() => setSelectedPost(post)}
                                >
                                  View Details
                                </Button>
                              </TableCell>
                            </TableRow>
                            {isExpanded && (
                              <TableRow key={`${post.id}-expanded`} className="border-b">
                                <TableCell colSpan={8} className="lg:hidden">
                                  <Card className="shadow-none border-0">
                                    <CardContent className="pt-4 pb-2">
                                      <div className="grid grid-cols-2 gap-3 text-sm">
                                        <div className="md:hidden">
                                          <p className="text-muted-foreground mb-1">Type</p>
                                          <span className="inline-block rounded-full bg-muted px-2 py-1 text-xs">
                                            {post.post_type}
                                          </span>
                                        </div>
                                        <div className="md:hidden">
                                          <p className="text-muted-foreground mb-1">Status</p>
                                          <span className="inline-block rounded-full bg-muted px-2 py-1 text-xs">
                                            {post.post_status}
                                          </span>
                                        </div>
                                        <div>
                                          <p className="text-muted-foreground mb-1">Words</p>
                                          <p className="font-medium tabular-nums">
                                            {post.word_count != null ? formatNumber(post.word_count) : 'N/A'}
                                          </p>
                                        </div>
                                        <div>
                                          <p className="text-muted-foreground mb-1">
                                            Reading Level
                                          </p>
                                          <p className="font-medium tabular-nums">
                                            {post.flesch_kincaid_grade !== null
                                              ? `Grade ${post.flesch_kincaid_grade.toFixed(1)}`
                                              : 'N/A'}
                                          </p>
                                        </div>
                                      </div>
                                    </CardContent>
                                  </Card>
                                </TableCell>
                              </TableRow>
                            )}
                          </Fragment>
                        );
                      })}
                    </TableBody>
                  </Table>
                </div>

                {/* Pagination */}
                <InertiaPagination
                  links={posts.links}
                  currentPage={posts.current_page}
                  lastPage={posts.last_page}
                />

                {/* Quality Score Detail Modal/Sidebar */}
                {selectedPost && (
                  <div
                    className="fixed inset-0 z-50 bg-background/80 backdrop-blur-sm"
                    onClick={() => setSelectedPost(null)}
                  >
                    <div
                      className="fixed right-0 top-0 h-full w-full max-w-md border-l bg-background p-6 shadow-lg overflow-y-auto"
                      onClick={(e) => e.stopPropagation()}
                    >
                      <div className="mb-4 flex items-start justify-between">
                        <div className="flex-1 pr-8">
                          <h2 className="text-lg font-semibold">{selectedPost.title}</h2>
                          <a
                            href={selectedPost.url}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-primary hover:underline mt-1"
                          >
                            View Page
                            <ExternalLink className="h-3 w-3" />
                          </a>
                        </div>
                        <Button variant="ghost" size="sm" onClick={() => setSelectedPost(null)}>
                          Close
                        </Button>
                      </div>

                      <div className="space-y-4">
                        <div className="grid grid-cols-2 gap-4 rounded-lg border p-4">
                          <div>
                            <p className="text-sm text-muted-foreground">Type</p>
                            <p className="font-medium">{selectedPost.post_type}</p>
                          </div>
                          <div>
                            <p className="text-sm text-muted-foreground">Status</p>
                            <p className="font-medium">{selectedPost.post_status}</p>
                          </div>
                          <div>
                            <p className="text-sm text-muted-foreground">Modified</p>
                            <p className="font-medium">
                              {selectedPost.wp_modified_at
                                ? formatDate(selectedPost.wp_modified_at)
                                : 'N/A'}
                            </p>
                          </div>
                          <div>
                            <p className="text-sm text-muted-foreground">WP Post ID</p>
                            <p className="font-medium">{selectedPost.wp_post_id}</p>
                          </div>
                        </div>

                        <QualityScoresCard
                          scores={{
                            flesch_kincaid_grade: selectedPost.flesch_kincaid_grade,
                            avg_sentence_length: selectedPost.avg_sentence_length,
                            paragraph_count: selectedPost.paragraph_count,
                            passive_voice_percentage: selectedPost.passive_voice_percentage,
                            word_count: selectedPost.word_count,
                            h1_count: selectedPost.h1_count,
                            h2_count: selectedPost.h2_count,
                            h3_count: selectedPost.h3_count,
                            h4_count: selectedPost.h4_count,
                            h5_count: selectedPost.h5_count,
                            h6_count: selectedPost.h6_count,
                            image_count: selectedPost.image_count,
                            internal_link_count: selectedPost.internal_link_count,
                            external_link_count: selectedPost.external_link_count,
                          }}
                        />
                      </div>
                    </div>
                  </div>
                )}
              </div>
            )}
          </>
        )}
      </div>
    </>
  );
}

ContentInventory.layout = (page: React.ReactElement) => <DashboardLayout>{page}</DashboardLayout>;
