import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { ShieldCheck, ShieldAlert, AlertTriangle } from 'lucide-react';
import PageHeader from '@/components/workshop/PageHeader';
import StatusPill from '@/components/workshop/StatusPill';
import LoadingPanel from '@/components/workshop/LoadingPanel';
import { projectService } from '@/services/projectService';
import { designService } from '@/services/designService';
import { ossiguardService } from '@/services/ossiguardService';
import { adapters } from '@/services/serviceConfig';

export default function Validation() {
  const [rows, setRows] = useState(null);

  useEffect(() => {
    (async () => {
      const projects = (await projectService.list()).filter((p) => p.record_state !== 'archived' && p.status !== 'Archived');
      const enriched = await Promise.all(projects.map(async (p) => {
        const [design, limb, ossiguard] = await Promise.all([
          designService.getCurrent(p.uuid),
          p.limb_profile_uuid ? adapters.database.filter('LimbProfile', { uuid: p.limb_profile_uuid }, '-updated_date', 1) : Promise.resolve([]),
          p.ossiguard_profile_uuid ? ossiguardService.get(p.ossiguard_profile_uuid) : Promise.resolve(null),
        ]);
        const designVal = design ? designService.validate(design, p, ossiguard) : { status: 'Blocked', issues: ['No design saved'] };
        const ossVal = ossiguard ? ossiguardService.validateProject(p, ossiguard, limb[0]) : null;
        const blocking = [...(designVal.issueObjects || []).filter((i) => i.level === 'blocked'), ...((ossVal?.issueObjects || []).filter((i) => i.level === 'blocked'))];
        return { project: p, design, ossiguard, designVal, ossVal, blocking };
      }));
      setRows(enriched);
    })();
  }, []);

  if (!rows) return <LoadingPanel label="Loading validation status" />;

  return (
    <>
      <PageHeader eyebrow="Workshop" title="Validation" description="Live validation status across all active cover projects — fit, design and Ossiguard compliance." />
      <div className="mb-4 rounded-lg border border-violet-400/30 bg-violet-400/5 p-3 text-xs text-violet-200"><ShieldCheck className="mr-1.5 inline h-4 w-4" />All SHiRE covers are non-load-bearing, cosmetic only. Validation confirms cosmetic compliance — never structural or body-weight capability.</div>
      {rows.length === 0 ? <div className="panel p-8 text-center text-slate-500">No active projects to validate.</div> : (
        <div className="space-y-3">
          {rows.map((r) => (
            <div key={r.project.uuid} className="panel p-4">
              <div className="flex flex-wrap items-center gap-2">
                <Link to={`/projects/${r.project.uuid}`} className="font-medium text-violet-200 hover:text-violet-100">{r.project.project_id}</Link>
                <StatusPill tone={r.project.status === 'Complete' ? 'green' : 'amber'}>{r.project.status}</StatusPill>
                <StatusPill tone={r.designVal.status === 'Pass' ? 'green' : r.designVal.status === 'Blocked' ? 'red' : 'amber'}>Design: {r.designVal.status}</StatusPill>
                {r.ossVal && <StatusPill tone={r.ossVal.level === 'pass' ? 'green' : r.ossVal.level === 'blocked' ? 'red' : 'amber'}>Ossiguard: {r.ossVal.status}</StatusPill>}
                {r.blocking.length === 0 && <StatusPill tone="green">No blocking issues</StatusPill>}
              </div>
              {r.blocking.length > 0 && (
                <div className="mt-3 space-y-1 rounded-lg border border-red-400/30 bg-red-400/5 p-3 text-xs text-red-200">
                  {r.blocking.map((b, i) => <div key={i} className="flex items-start gap-2"><ShieldAlert className="mt-0.5 h-3.5 w-3.5 shrink-0" />{b.text}</div>)}
                </div>
              )}
              {r.designVal.issues && r.designVal.issues.length > 0 && (
                <details className="mt-2 text-xs text-slate-400"><summary className="cursor-pointer text-slate-500">{r.designVal.issues.length} design issues</summary><ul className="mt-2 space-y-1">{r.designVal.issues.map((i, idx) => <li key={idx} className="flex items-start gap-2"><AlertTriangle className="mt-0.5 h-3 w-3 shrink-0 text-amber-400" />{i}</li>)}</ul></details>
              )}
            </div>
          ))}
        </div>
      )}
    </>
  );
}