import React, { useRef, useEffect, useState } from 'react';
import { gsap, ScrollTrigger } from '../lib/gsap.ts';
import { useReducedMotion } from '../hooks/useReducedMotion.ts';
import { DiagnosticCard } from '../components/diagnostics/DiagnosticCard.tsx';
import { StatePanel } from '../components/diagnostics/StatePanel.tsx';
import { healthChecks } from '../data/incidents.ts';

const DiagnosticsPage: React.FC = () => {
  const reduced = useReducedMotion();
  const pinnedRef = useRef<HTMLDivElement>(null);
  const [checks, setChecks] = useState(healthChecks.map(c => ({ ...c, status: 'pending' as const })));

  useEffect(() => {
    if (reduced) {
      setChecks(healthChecks.map(c => ({ ...c, status: 'pass' as const })));
      return;
    }
    const ctx = gsap.context(() => {
      if (pinnedRef.current) {
        const phases = pinnedRef.current.querySelectorAll('.phase');
        gsap.fromTo(phases, { opacity: 0, y: 30 }, {
          opacity: 1, y: 0,
          stagger: 0.3,
          scrollTrigger: {
            trigger: pinnedRef.current,
            start: 'top center',
            end: 'bottom center',
            scrub: true,
            onUpdate: (self) => {
              const index = Math.min(Math.floor(self.progress * healthChecks.length), healthChecks.length - 1);
              setChecks(prev => prev.map((c, i) => ({
                ...c,
                status: i <= index ? 'pass' as const : 'pending' as const,
              })));
            },
          },
        });
      }
    });
    return () => ctx.revert();
  }, [reduced]);

  return (
    <div className="container mx-auto px-4 py-24">
      <h1 className="text-4xl font-display font-bold text-[var(--ink)] mb-2">Load Failure Diagnostics</h1>
      <p className="text-[var(--ink-muted)] mb-8">
        All known failure modes are checked and resolved.
      </p>

      <div ref={pinnedRef} className="space-y-4 mb-16">
        {checks.map((check) => (
          <div key={check.id} className="phase">
            <DiagnosticCard label={check.label} status={check.status} message={`${check.label} check completed.`} />
          </div>
        ))}
      </div>

      <section className="py-8 border-t border-[var(--border)]">
        <h2 className="text-2xl font-display font-bold text-[var(--ink)] mb-6">State Panel Examples</h2>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
          <StatePanel type="loading" />
          <StatePanel type="empty" title="No diagnostics available" description="All checks have passed and no issues remain." />
          <StatePanel type="error" description="A simulated error occurred. Use the retry button to recover." onRetry={() => alert('Retrying...')} />
          <StatePanel type="success" title="All Systems Operational" description="Every component passed validation." />
        </div>
      </section>
    </div>
  );
};

export default DiagnosticsPage;