import { RefreshCw } from 'lucide-react';

import { useEffect, useRef } from 'react';

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


import DecayPatternBadge from '@/Components/ContentIntelligence/DecayPatternBadge';
import FreshnessScoreCard from '@/Components/ContentIntelligence/FreshnessScoreCard';
import SiteNav from '@/Components/Navigation/SiteNav';
import { Badge } from '@/Components/ui/badge';
import { Button } from '@/Components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/Components/ui/card';
import { EmptyState } from '@/Components/ui/empty-state';
import { Input } from '@/Components/ui/input';
import { Label } from '@/Components/ui/label';
import { LoadingButton } from '@/Components/ui/loading-button';
import {
  Pagination,
  PaginationContent,
  PaginationEllipsis,
  PaginationItem,
  PaginationLink,
  PaginationNext,
  PaginationPrevious,
} from '@/Components/ui/pagination';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/Components/ui/select';
import { Skeleton } from '@/Components/ui/skeleton';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/Components/ui/table';
import { usePolling } from '@/hooks/usePolling';
import { useSiteKeyboardShortcuts } from '@/hooks/useSiteKeyboardShortcuts';
import DashboardLayout from '@/Layouts/DashboardLayout';
import { trackFilterApplied, trackProductEvent } from '@/lib/analytics';
import { FRESHNESS_VIEWED } from '@/lib/event-catalog';
import { formatDateOnly, formatPercent } from '@/lib/format';
import type { PageProps } from '@/types';
import type { FreshnessIndexPageProps } from '@/types/freshness';

export default function FreshnessIndex({
  site,
  latestRun,
  recommendations,
  filters,
  counts,
}: FreshnessIndexPageProps) {
  const { polling_interval_ms } = usePage<PageProps>().props;

  useEffect(() => {
    trackProductEvent(FRESHNESS_VIEWED, { site_id: String(site.id) });
  }, [site.id]);

  // Poll when analysis is in progress
  usePolling(
    !!latestRun?.status && ['pending', 'processing'].includes(latestRun.status),
    polling_interval_ms,
    ['latestRun', 'recommendations', 'counts'],
  );

  // Form for triggering new analysis
  const { data, setData, post, processing, errors } = useForm({
    analysis_window_start: latestRun?.analysis_window_start ?? '',
    analysis_window_end: latestRun?.analysis_window_end ?? '',
  });

  const handleTriggerAnalysis = (e: React.FormEvent) => {
    e.preventDefault();
    post(route('freshness.store', site.id));
  };

  // Handle filter changes
  const handleFilterChange = (key: string, value: string | undefined) => {
    if (value) {
      trackFilterApplied(key, value);
    }
    router.get(
      route('freshness.index', site.id),
      {
        ...filters,
        [key]: value || undefined,
      },
      {
        preserveState: true,
        replace: true,
      },
    );
  };

  // Handle page navigation
  const handlePage = (page: number) => {
    router.get(
      route('freshness.index', site.id),
      {
        ...filters,
        page,
      },
      {
        preserveState: true,
        replace: true,
      },
    );
  };

  // Keyboard shortcuts
  const firstFilterRef = useRef<HTMLButtonElement>(null);
  const currentPage = recommendations?.current_page ?? 1;
  const lastPage = recommendations?.last_page ?? 1;

  useSiteKeyboardShortcuts({
    onSearch: () => firstFilterRef.current?.click(),
    onNextPage: currentPage < lastPage ? () => handlePage(currentPage + 1) : undefined,
    onPrevPage: currentPage > 1 ? () => handlePage(currentPage - 1) : undefined,
  });

  return (
    <>
      <Head title={`${site.name} - Freshness Watchlist`} />

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

        <div className="flex items-center justify-between mb-6">
          <div>
            <h1 className="text-2xl font-bold tracking-tight">Freshness Watchlist</h1>
            <p className="text-sm text-muted-foreground mt-1">
              Track pages losing performance due to staleness
            </p>
          </div>
        </div>

        {/* Trigger Analysis Form */}
        <Card className="mb-6">
          <CardHeader>
            <CardTitle>Run Freshness Analysis</CardTitle>
            <CardDescription>Detect decay patterns and get refresh recommendations</CardDescription>
          </CardHeader>
          <CardContent>
            <form onSubmit={handleTriggerAnalysis} className="space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="analysis_window_start">Analysis Window Start</Label>
                  <Input
                    id="analysis_window_start"
                    type="date"
                    value={data.analysis_window_start}
                    onChange={(e) => setData('analysis_window_start', e.target.value)}
                    disabled={processing}
                  />
                  {errors.analysis_window_start && (
                    <p className="text-sm text-destructive">{errors.analysis_window_start}</p>
                  )}
                </div>
                <div className="space-y-2">
                  <Label htmlFor="analysis_window_end">Analysis Window End</Label>
                  <Input
                    id="analysis_window_end"
                    type="date"
                    value={data.analysis_window_end}
                    onChange={(e) => setData('analysis_window_end', e.target.value)}
                    disabled={processing}
                  />
                  {errors.analysis_window_end && (
                    <p className="text-sm text-destructive">{errors.analysis_window_end}</p>
                  )}
                </div>
              </div>
              <LoadingButton type="submit" loading={processing}>
                <RefreshCw className="mr-2 h-4 w-4" />
                Run Analysis
              </LoadingButton>
            </form>
          </CardContent>
        </Card>

        {/* Latest Run Status */}
        {latestRun && (
          <div className="mb-6">
            {(latestRun.status === 'processing' || latestRun.status === 'pending') && (
              <Card className="border-info/30 bg-info/10">
                <CardContent className="pt-6">
                  <div className="flex items-center gap-4">
                    <RefreshCw className="h-5 w-5 animate-spin text-info" />
                    <div>
                      <p className="font-medium text-info">Analysis in Progress</p>
                      <p className="text-sm text-info/80">
                        Analyzing pages from {latestRun.analysis_window_start} to{' '}
                        {latestRun.analysis_window_end}...
                      </p>
                    </div>
                  </div>
                </CardContent>
              </Card>
            )}

            {latestRun.status === 'failed' && (
              <Card className="border-destructive/30 bg-destructive/10">
                <CardContent className="pt-6">
                  <div>
                    <h3 className="text-sm font-medium text-destructive mb-2">Analysis Failed</h3>
                    <p className="text-sm text-destructive/80">
                      The freshness analysis could not be completed. Try again.
                    </p>
                  </div>
                </CardContent>
              </Card>
            )}

            {latestRun.status === 'completed' && latestRun.summary && (
              <Card>
                <CardHeader>
                  <CardTitle>Latest Analysis Summary</CardTitle>
                  <CardDescription>
                    Completed on{' '}
                    {latestRun.completed_at ? formatDateOnly(latestRun.completed_at) : 'Unknown'}
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
                    <div>
                      <p className="text-sm text-muted-foreground">Total</p>
                      <p className="text-2xl font-bold">{counts.total}</p>
                    </div>
                    <div>
                      <p className="text-sm text-muted-foreground">Light Refresh</p>
                      <p className="text-2xl font-bold">{counts.light_refresh}</p>
                    </div>
                    <div>
                      <p className="text-sm text-muted-foreground">Section Refresh</p>
                      <p className="text-2xl font-bold">{counts.section_refresh}</p>
                    </div>
                    <div>
                      <p className="text-sm text-muted-foreground">Full Rewrite</p>
                      <p className="text-2xl font-bold">{counts.full_rewrite}</p>
                    </div>
                    <div>
                      <p className="text-sm text-muted-foreground">Reposition Intent</p>
                      <p className="text-2xl font-bold">{counts.reposition_intent}</p>
                    </div>
                  </div>
                </CardContent>
              </Card>
            )}
          </div>
        )}

        {/* Filters */}
        {latestRun?.status === 'completed' && recommendations.total > 0 && (
          <Card className="mb-6">
            <CardHeader>
              <CardTitle>Filters</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="action_type">Action Type</Label>
                  <Select
                    value={filters.action_type || 'all'}
                    onValueChange={(value) =>
                      handleFilterChange('action_type', value === 'all' ? undefined : value)
                    }
                  >
                    <SelectTrigger id="action_type" ref={firstFilterRef}>
                      <SelectValue placeholder="All types" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">All types</SelectItem>
                      <SelectItem value="light_refresh">Light Refresh</SelectItem>
                      <SelectItem value="section_refresh">Section Refresh</SelectItem>
                      <SelectItem value="full_rewrite">Full Rewrite</SelectItem>
                      <SelectItem value="reposition_intent">Reposition Intent</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="decay_pattern">Decay Pattern</Label>
                  <Select
                    value={filters.decay_pattern || 'all'}
                    onValueChange={(value) =>
                      handleFilterChange('decay_pattern', value === 'all' ? undefined : value)
                    }
                  >
                    <SelectTrigger id="decay_pattern">
                      <SelectValue placeholder="All patterns" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">All patterns</SelectItem>
                      <SelectItem value="gradual_decay">Gradual Decay</SelectItem>
                      <SelectItem value="step_drop">Step Drop</SelectItem>
                      <SelectItem value="post_update_decline">Post-Update Decline</SelectItem>
                      <SelectItem value="query_mix_erosion">Query Mix Erosion</SelectItem>
                      <SelectItem value="position_drift">Position Drift</SelectItem>
                      <SelectItem value="seasonal_normalized_decay">Seasonal Decay</SelectItem>
                      <SelectItem value="volatility">Volatility</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="min_confidence">Min Confidence</Label>
                  <Select
                    value={String(filters.min_confidence || 'all')}
                    onValueChange={(value) =>
                      handleFilterChange('min_confidence', value === 'all' ? undefined : value)
                    }
                  >
                    <SelectTrigger id="min_confidence">
                      <SelectValue placeholder="All confidence" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">All confidence</SelectItem>
                      <SelectItem value="0.7">High (70%+)</SelectItem>
                      <SelectItem value="0.5">Medium (50%+)</SelectItem>
                      <SelectItem value="0.3">Low (30%+)</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="sort_by">Sort By</Label>
                  <Select
                    value={filters.sort_by || 'impact'}
                    onValueChange={(value) => handleFilterChange('sort_by', value)}
                  >
                    <SelectTrigger id="sort_by">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="impact">Impact</SelectItem>
                      <SelectItem value="urgency">Urgency</SelectItem>
                      <SelectItem value="effort">Effort</SelectItem>
                      <SelectItem value="freshness">Freshness</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>

              {(filters.action_type || filters.decay_pattern || filters.min_confidence) && (
                <div className="mt-4">
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() =>
                      router.get(
                        route('freshness.index', site.id),
                        {},
                        { preserveState: true, replace: true },
                      )
                    }
                  >
                    Clear Filters
                  </Button>
                </div>
              )}
            </CardContent>
          </Card>
        )}

        {/* Recommendations Table */}
        {!latestRun && (
          <EmptyState
            title="Run your first freshness analysis"
            description="Detect pages losing traffic to staleness and get targeted refresh recommendations. Set a date range above and click Run Analysis."
          />
        )}

        {latestRun && (latestRun.status === 'processing' || latestRun.status === 'pending') && (
          <Card>
            <CardContent className="pt-6">
              <div className="space-y-3">
                <Skeleton className="h-10 w-full" />
                <Skeleton className="h-10 w-full" />
                <Skeleton className="h-10 w-full" />
              </div>
            </CardContent>
          </Card>
        )}

        {latestRun?.status === 'completed' && recommendations.total === 0 && (
          <EmptyState
            title="No recommendations found"
            description="No pages with decay patterns were detected in this analysis period."
          />
        )}

        {latestRun?.status === 'completed' && recommendations.total > 0 && (
          <>
            <Card>
              <div className="overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Page</TableHead>
                      <TableHead>Decay Pattern</TableHead>
                      <TableHead>Freshness Score</TableHead>
                      <TableHead>Loss Estimate</TableHead>
                      <TableHead>Recommended Action</TableHead>
                      <TableHead>Confidence</TableHead>
                      <TableHead className="w-[50px]"></TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {recommendations.data.map((rec) => (
                      <TableRow key={rec.id}>
                        <TableCell>
                          <div className="max-w-xs">
                            <p className="font-medium truncate">{rec.title}</p>
                            <p className="text-xs text-muted-foreground truncate">{rec.page_url}</p>
                          </div>
                        </TableCell>
                        <TableCell>
                          {rec.page_decay_signal && (
                            <DecayPatternBadge pattern={rec.page_decay_signal.decay_pattern_type} />
                          )}
                        </TableCell>
                        <TableCell>
                          <FreshnessScoreCard score={rec.freshness_score} />
                        </TableCell>
                        <TableCell>
                          {rec.page_decay_signal && (
                            <div>
                              <p className="font-medium text-destructive">
                                {formatPercent(rec.page_decay_signal.decay_magnitude / 100)}
                              </p>
                              <p className="text-xs text-muted-foreground">
                                Current: {Math.round(rec.page_decay_signal.current_clicks)}{' '}
                                clicks/day
                              </p>
                            </div>
                          )}
                        </TableCell>
                        <TableCell>
                          <Badge variant="outline">
                            {rec.action_type
                              .split('_')
                              .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
                              .join(' ')}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          <div className="text-sm">{Math.round(rec.confidence_score * 100)}%</div>
                        </TableCell>
                        <TableCell>
                          <Button variant="ghost" size="sm" asChild>
                            <Link
                              href={route('freshness.show', {
                                site: site.id,
                                freshnessRecommendation: rec.id,
                              })}
                            >
                              View
                            </Link>
                          </Button>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </Card>

            {/* Pagination */}
            {recommendations.last_page > 1 && (
              <div className="mt-6">
                <Pagination>
                  <PaginationContent>
                    {recommendations.current_page > 1 && (
                      <PaginationItem>
                        <PaginationPrevious
                          href={route('freshness.index', {
                            site: site.id,
                            page: recommendations.current_page - 1,
                            ...filters,
                          })}
                        />
                      </PaginationItem>
                    )}

                    {Array.from({ length: recommendations.last_page }).map((_, idx) => {
                      const page = idx + 1;
                      if (
                        page === 1 ||
                        page === recommendations.last_page ||
                        Math.abs(page - recommendations.current_page) <= 1
                      ) {
                        return (
                          <PaginationItem key={page}>
                            <PaginationLink
                              href={route('freshness.index', {
                                site: site.id,
                                page,
                                ...filters,
                              })}
                              isActive={page === recommendations.current_page}
                            >
                              {page}
                            </PaginationLink>
                          </PaginationItem>
                        );
                      } else if (Math.abs(page - recommendations.current_page) === 2) {
                        return (
                          <PaginationItem key={page}>
                            <PaginationEllipsis />
                          </PaginationItem>
                        );
                      }
                      return null;
                    })}

                    {recommendations.current_page < recommendations.last_page && (
                      <PaginationItem>
                        <PaginationNext
                          href={route('freshness.index', {
                            site: site.id,
                            page: recommendations.current_page + 1,
                            ...filters,
                          })}
                        />
                      </PaginationItem>
                    )}
                  </PaginationContent>
                </Pagination>
              </div>
            )}
          </>
        )}
      </div>
    </>
  );
}

FreshnessIndex.layout = (page: React.ReactNode) => <DashboardLayout>{page}</DashboardLayout>;
