import { AlertTriangle, Filter, X } from 'lucide-react';

import { useEffect, useState } from 'react';

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

import { FeatureGateTeaser } from '@/Components/billing/FeatureGateTeaser';
import SiteNav from '@/Components/Navigation/SiteNav';
import InertiaPagination from '@/Components/Shared/InertiaPagination';
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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/Components/ui/select';
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetTrigger } from '@/Components/ui/sheet';
import DashboardLayout from '@/Layouts/DashboardLayout';
import { trackProductEvent } from '@/lib/analytics';
import { TRAFFIC_ALERTS_VIEWED } from '@/lib/event-catalog';
import { formatDateOnly, truncateUrl } from '@/lib/format';
import { ALERT_STATUS_LABELS as STATUS_LABELS } from '@/lib/status';
import { cn } from '@/lib/utils';
import type { PageProps, TrafficAlert, SiteBasic } from '@/types';

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

interface Filters {
  severity: string | null;
  status: string | null;
  anomaly_type: string | null;
  start_date: string | null;
  end_date: string | null;
  sort_by: string | null;
}

interface Counts {
  total: number;
  unacknowledged: number;
  acknowledged: number;
  dismissed: number;
  critical: number;
  warning: number;
  info: number;
}

interface TrafficAlertsIndexPageProps {
  site: SiteBasic;
  alerts: PaginatedAlerts;
  filters: Filters;
  counts: Counts;
}

const SEVERITY_LABELS: Record<string, string> = {
  critical: 'Critical',
  warning: 'Warning',
  info: 'Info',
};

const ANOMALY_TYPE_LABELS: Record<string, string> = {
  sudden_drop: 'Sudden Drop',
  sustained_decline: 'Sustained Decline',
  unusual_spike: 'Unusual Spike',
};

function buildFilterUrl(siteId: number, filters: Filters, updates: Partial<Filters>): string {
  const baseUrl = route('alerts.index', siteId);
  const params = new URLSearchParams();

  const newFilters = { ...filters, ...updates };

  if (newFilters.severity) params.set('severity', newFilters.severity);
  if (newFilters.status) params.set('status', newFilters.status);
  if (newFilters.anomaly_type) params.set('anomaly_type', newFilters.anomaly_type);
  if (newFilters.start_date) params.set('start_date', newFilters.start_date);
  if (newFilters.end_date) params.set('end_date', newFilters.end_date);
  if (newFilters.sort_by) params.set('sort_by', newFilters.sort_by);

  const qs = params.toString();
  return qs ? `${baseUrl}?${qs}` : baseUrl;
}

function buildClearFilterUrl(siteId: number, filters: Filters, keyToClear: string): string {
  const updates: Partial<Filters> = { [keyToClear]: null };
  return buildFilterUrl(siteId, filters, updates);
}

function getSeverityBadgeVariant(severity: string): 'default' | 'destructive' | 'secondary' {
  switch (severity) {
    case 'critical':
      return 'destructive';
    case 'warning':
      return 'default';
    case 'info':
      return 'secondary';
    default:
      return 'default';
  }
}

function formatDelta(delta: number): string {
  const sign = delta > 0 ? '+' : '';
  return `${sign}${delta.toFixed(1)}%`;
}

export default function TrafficAlertsIndex({
  site,
  alerts,
  filters,
  counts,
}: TrafficAlertsIndexPageProps) {
  const { plan } = usePage<PageProps>().props;
  const isFreeUser = !plan || plan === 'free';
  const [mobileFiltersOpen, setMobileFiltersOpen] = useState(false);

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

  const handleFilterChange = (key: keyof Filters, value: string | undefined) => {
    router.get(
      buildFilterUrl(site.id, filters, { [key]: value || null }),
      {},
      {
        preserveState: true,
        replace: true,
      },
    );
  };

  const clearAllFiltersUrl = route('alerts.index', site.id);

  // Active filter chips
  const activeFilterChips: Array<{ key: string; label: string; clearUrl: string }> = [];
  if (filters.severity) {
    activeFilterChips.push({
      key: 'severity',
      label: `Severity: ${SEVERITY_LABELS[filters.severity] ?? filters.severity}`,
      clearUrl: buildClearFilterUrl(site.id, filters, 'severity'),
    });
  }
  if (filters.status) {
    activeFilterChips.push({
      key: 'status',
      label: `Status: ${STATUS_LABELS[filters.status] ?? filters.status}`,
      clearUrl: buildClearFilterUrl(site.id, filters, 'status'),
    });
  }
  if (filters.anomaly_type) {
    activeFilterChips.push({
      key: 'anomaly_type',
      label: `Type: ${ANOMALY_TYPE_LABELS[filters.anomaly_type] ?? filters.anomaly_type}`,
      clearUrl: buildClearFilterUrl(site.id, filters, 'anomaly_type'),
    });
  }
  if (filters.start_date || filters.end_date) {
    const dateLabel =
      filters.start_date && filters.end_date
        ? `${filters.start_date} to ${filters.end_date}`
        : filters.start_date
          ? `From ${filters.start_date}`
          : `Until ${filters.end_date}`;
    activeFilterChips.push({
      key: 'date_range',
      label: `Dates: ${dateLabel}`,
      clearUrl: buildFilterUrl(site.id, filters, { start_date: null, end_date: null }),
    });
  }

  const hasActiveFilters = activeFilterChips.length > 0;

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

      <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">Traffic Alerts</h1>
            <p className="text-sm text-muted-foreground mt-1">
              Monitor and respond to traffic anomalies detected in your analysis
            </p>
          </div>
        </div>

        {/* Stats Cards */}
        <div className="grid gap-4 md:grid-cols-4 lg:grid-cols-7 mb-6">
          <Card aria-label={`Total alerts: ${counts.total}`}>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Total</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{counts.total}</div>
            </CardContent>
          </Card>
          <Card
            aria-label={`Unacknowledged alerts: ${counts.unacknowledged}`}
            className={cn(
              counts.unacknowledged > 0 && 'border-orange-200 bg-orange-50 dark:bg-orange-950/20',
            )}
          >
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Unacknowledged</CardTitle>
            </CardHeader>
            <CardContent>
              <div
                className={cn(
                  'text-2xl font-bold',
                  counts.unacknowledged > 0 && 'text-orange-600 dark:text-orange-400',
                )}
              >
                {counts.unacknowledged}
              </div>
            </CardContent>
          </Card>
          <Card aria-label={`Acknowledged alerts: ${counts.acknowledged}`}>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Acknowledged</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{counts.acknowledged}</div>
            </CardContent>
          </Card>
          <Card aria-label={`Dismissed alerts: ${counts.dismissed}`}>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Dismissed</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{counts.dismissed}</div>
            </CardContent>
          </Card>
          <Card
            aria-label={`Critical alerts: ${counts.critical}`}
            className={cn(counts.critical > 0 && 'border-destructive/20 bg-destructive/5')}
          >
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Critical</CardTitle>
            </CardHeader>
            <CardContent>
              <div className={cn('text-2xl font-bold', counts.critical > 0 && 'text-destructive')}>
                {counts.critical}
              </div>
            </CardContent>
          </Card>
          <Card aria-label={`Warning alerts: ${counts.warning}`}>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Warning</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{counts.warning}</div>
            </CardContent>
          </Card>
          <Card aria-label={`Info alerts: ${counts.info}`}>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Info</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{counts.info}</div>
            </CardContent>
          </Card>
        </div>

        {/* Filters */}
        <Card className="mb-6">
          <CardHeader>
            <div className="flex items-center justify-between">
              <div>
                <CardTitle>Filters</CardTitle>
                <CardDescription>Filter alerts by severity, status, type, and date</CardDescription>
              </div>
              <Sheet open={mobileFiltersOpen} onOpenChange={setMobileFiltersOpen}>
                <SheetTrigger asChild>
                  <Button variant="outline" size="sm" className="md:hidden">
                    <Filter className="h-4 w-4 mr-2" />
                    Filters
                  </Button>
                </SheetTrigger>
                <SheetContent>
                  <SheetHeader>
                    <SheetTitle>Filter Alerts</SheetTitle>
                  </SheetHeader>
                  <div className="mt-6 space-y-4">
                    <FilterControls filters={filters} onFilterChange={handleFilterChange} />
                  </div>
                </SheetContent>
              </Sheet>
            </div>
          </CardHeader>
          <CardContent>
            <div className="hidden md:block">
              <FilterControls filters={filters} onFilterChange={handleFilterChange} />
            </div>

            {/* Active Filters */}
            {hasActiveFilters && (
              <div className="flex flex-wrap gap-2 mt-4 pt-4 border-t">
                <span className="text-sm font-medium">Active Filters:</span>
                {activeFilterChips.map((chip) => (
                  <Badge key={chip.key} variant="secondary" className="gap-1">
                    {chip.label}
                    <Link href={chip.clearUrl} preserveState replace>
                      <X className="h-3 w-3" />
                    </Link>
                  </Badge>
                ))}
                <Link href={clearAllFiltersUrl}>
                  <Button variant="ghost" size="sm">
                    Clear All
                  </Button>
                </Link>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Pro feature teaser for free users */}
        {isFreeUser && (
          <div className="mb-6">
            <FeatureGateTeaser
              featureName="Traffic Anomaly Alerts"
              description="Get notified automatically when traffic drops >20%, sustains a multi-week decline, or spikes unexpectedly — so you can respond before rankings slip further."
              ctaLabel="Unlock Anomaly Alerts"
            />
          </div>
        )}

        {/* Alert List */}
        {alerts.data.length === 0 ? (
          <EmptyState
            icon={AlertTriangle}
            title="No traffic alerts"
            description={
              hasActiveFilters
                ? 'No alerts match your current filters. Try adjusting your filter criteria.'
                : 'No traffic anomalies detected yet. Alerts will appear here when unusual traffic patterns are detected in your analysis.'
            }
          />
        ) : (
          <>
            <div className="space-y-4">
              {alerts.data.map((alert) => (
                <AlertCard key={alert.id} alert={alert} siteId={site.id} />
              ))}
            </div>

            {/* Pagination */}
            {alerts.data.length > 0 && (
              <div className="mt-6">
                <InertiaPagination
                  links={alerts.links}
                  currentPage={alerts.current_page}
                  lastPage={alerts.last_page}
                />
              </div>
            )}
          </>
        )}
      </div>
    </>
  );
}

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

// Filter Controls Component
interface FilterControlsProps {
  filters: Filters;
  onFilterChange: (key: keyof Filters, value: string | undefined) => void;
}

function FilterControls({ filters, onFilterChange }: FilterControlsProps) {
  return (
    <div className="grid grid-cols-1 md:grid-cols-5 gap-4">
      <div className="space-y-2">
        <Label htmlFor="severity-filter">Severity</Label>
        <Select
          value={filters.severity ?? 'all'}
          onValueChange={(value) => onFilterChange('severity', value === 'all' ? undefined : value)}
        >
          <SelectTrigger id="severity-filter">
            <SelectValue placeholder="All severities" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All Severities</SelectItem>
            <SelectItem value="critical">Critical</SelectItem>
            <SelectItem value="warning">Warning</SelectItem>
            <SelectItem value="info">Info</SelectItem>
          </SelectContent>
        </Select>
      </div>

      <div className="space-y-2">
        <Label htmlFor="status-filter">Status</Label>
        <Select
          value={filters.status ?? 'all'}
          onValueChange={(value) => onFilterChange('status', value === 'all' ? undefined : value)}
        >
          <SelectTrigger id="status-filter">
            <SelectValue placeholder="All statuses" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All Statuses</SelectItem>
            <SelectItem value="unacknowledged">Unacknowledged</SelectItem>
            <SelectItem value="acknowledged">Acknowledged</SelectItem>
            <SelectItem value="dismissed">Dismissed</SelectItem>
          </SelectContent>
        </Select>
      </div>

      <div className="space-y-2">
        <Label htmlFor="anomaly-type-filter">Anomaly Type</Label>
        <Select
          value={filters.anomaly_type ?? 'all'}
          onValueChange={(value) =>
            onFilterChange('anomaly_type', value === 'all' ? undefined : value)
          }
        >
          <SelectTrigger id="anomaly-type-filter">
            <SelectValue placeholder="All types" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All Types</SelectItem>
            <SelectItem value="sudden_drop">Sudden Drop</SelectItem>
            <SelectItem value="sustained_decline">Sustained Decline</SelectItem>
            <SelectItem value="unusual_spike">Unusual Spike</SelectItem>
          </SelectContent>
        </Select>
      </div>

      <div className="space-y-2">
        <Label htmlFor="start-date">Start Date</Label>
        <Input
          id="start-date"
          type="date"
          value={filters.start_date ?? ''}
          onChange={(e) => {
            const val = e.target.value;
            if (!val || val.length === 10) onFilterChange('start_date', val || undefined);
          }}
        />
      </div>

      <div className="space-y-2">
        <Label htmlFor="end-date">End Date</Label>
        <Input
          id="end-date"
          type="date"
          value={filters.end_date ?? ''}
          onChange={(e) => {
            const val = e.target.value;
            if (!val || val.length === 10) onFilterChange('end_date', val || undefined);
          }}
        />
      </div>
    </div>
  );
}

// Alert Card Component
interface AlertCardProps {
  alert: TrafficAlert;
  siteId: number;
}

function AlertCard({ alert, siteId }: AlertCardProps) {
  return (
    <Card
      className={cn(
        alert.severity === 'critical' && 'border-destructive/20 bg-destructive/5',
        alert.severity === 'warning' && 'border-warning/20 bg-warning/5',
      )}
    >
      <CardContent className="pt-6">
        <div className="flex items-start justify-between gap-4">
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2 mb-2">
              <Badge variant={getSeverityBadgeVariant(alert.severity)}>
                {SEVERITY_LABELS[alert.severity]}
              </Badge>
              <Badge variant="outline">{ANOMALY_TYPE_LABELS[alert.anomaly_type]}</Badge>
              {alert.created_at && (
                <span className="text-sm text-muted-foreground">
                  {formatDateOnly(alert.created_at)}
                </span>
              )}
            </div>

            <div className="mb-3">
              <a
                href={alert.page_url}
                target="_blank"
                rel="noopener noreferrer"
                className="text-sm font-medium hover:underline break-all"
                title={alert.page_url}
              >
                {truncateUrl(alert.page_url, 80)}
              </a>
            </div>

            <div className="flex gap-4 text-sm">
              <div>
                <span className="text-muted-foreground">Clicks: </span>
                <span className="font-medium">
                  {alert.metrics.clicks_before} → {alert.metrics.clicks_after}
                </span>
                <span
                  className={cn(
                    'ml-2 font-semibold',
                    alert.metrics.delta_percent < 0 ? 'text-destructive' : 'text-success',
                  )}
                >
                  ({formatDelta(alert.metrics.delta_percent)})
                </span>
              </div>
            </div>
          </div>

          <div className="flex gap-2">
            <Button variant="outline" size="sm" asChild>
              <Link href={route('alerts.show', [siteId, alert.id])}>View Details</Link>
            </Button>
          </div>
        </div>
      </CardContent>
    </Card>
  );
}
