import React, { useState, useEffect, useRef } from 'react';
import { gsap, ScrollTrigger } from '../lib/gsap.ts';
import { useReducedMotion } from '../hooks/useReducedMotion.ts';
import { IncidentCard } from '../components/diagnostics/IncidentCard.tsx';
import { Skeleton } from '../components/ui/Skeleton.tsx';
import { EmptyState } from '../components/ui/EmptyState.tsx';
import { ErrorState } from '../components/ui/ErrorState.tsx';
import { Input } from '../components/ui/Input.tsx';
import { Select } from '../components/ui/Select.tsx';
import { incidents, healthChecks } from '../data/incidents.ts';
import { IncidentSchema } from '../data/schema.ts';

const IncidentsPage: React.FC = () => {
  const reduced = useReducedMotion();
  const scrollRef = useRef<HTMLDivElement>(null);
  const [search, setSearch] = useState('');
  const [severity, setSeverity] = useState('all');
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);

  useEffect(() => {
    const timer = setTimeout(() => {
      try {
        incidents.forEach(inc => IncidentSchema.parse(inc));
      } catch {
        setError(true);
      }
      setLoading(false);
    }, 300);
    return () => clearTimeout(timer);
  }, []);

  useEffect(() => {
    if (reduced || loading || !scrollRef.current) return;
    const ctx = gsap.context(() => {
      const cards = scrollRef.current?.children;
      if (cards) {
        gsap.to(scrollRef.current, {
          xPercent: -50,
          ease: 'none',
          scrollTrigger: {
            trigger: scrollRef.current?.parentElement,
            start: 'top bottom',
            end: 'bottom top',
            scrub: 1,
          },
        });
      }
    }, scrollRef);
    return () => ctx.revert();
  }, [reduced, loading]);

  const filtered = incidents.filter(inc => {
    const matchSearch = inc.name.toLowerCase().includes(search.toLowerCase()) ||
      inc.description.toLowerCase().includes(search.toLowerCase());
    const matchSeverity = severity === 'all' || inc.severity === severity;
    return matchSearch && matchSeverity;
  });

  if (error) {
    return (
      <div className="container mx-auto px-4 py-24">
        <h1 className="text-4xl font-display font-bold mb-8">Incident Log</h1>
        <ErrorState onRetry={() => { setError(false); setLoading(true); setTimeout(() => setLoading(false), 300); }} />
      </div>
    );
  }

  return (
    <div className="container mx-auto px-4 py-24">
      <h1 className="text-4xl font-display font-bold mb-2">Incident Log</h1>
      <p className="text-[var(--ink-muted)] mb-8">
        A record of all blank-screen failure modes and their resolution.
      </p>

      <div className="flex flex-col md:flex-row gap-4 mb-8">
        <Input
          placeholder="Search incidents..."
          value={search}
          onChange={(e) => setSearch(e.target.value)}
        />
        <Select
          options={[
            { value: 'all', label: 'All Severities' },
            { value: 'critical', label: 'Critical' },
            { value: 'high', label: 'High' },
            { value: 'medium', label: 'Medium' },
            { value: 'low', label: 'Low' },
          ]}
          value={severity}
          onChange={(e) => setSeverity(e.target.value)}
        />
      </div>

      {loading ? (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {Array.from({ length: 6 }).map((_, i) => (
            <div key={i} className="space-y-4">
              <Skeleton className="h-32 w-full" />
              <Skeleton className="h-4 w-3/4" />
              <Skeleton className="h-4 w-1/2" />
            </div>
          ))}
        </div>
      ) : filtered.length === 0 ? (
        <EmptyState title="No incidents found" description="Try adjusting your filters." />
      ) : (
        <div ref={scrollRef} className="flex gap-6 overflow-x-auto pb-4">
          {filtered.map(inc => (
            <IncidentCard key={inc.id} incident={inc} />
          ))}
        </div>
      )}
    </div>
  );
};

export default IncidentsPage;