import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { ShieldCheck, Play, LockKeyhole, CheckCircle2, AlertTriangle, XCircle, Clock3, ChevronDown, Activity, Wrench, Eye } from 'lucide-react';
import { base44 } from '@/api/base44Client';
import PageHeader from '@/components/app/PageHeader';
import StatusBadge from '@/components/app/StatusBadge';
import { useExperienceMode } from '@/lib/ExperienceMode';
import { GeometryService, buildGeometryRequest } from '@/lib/geometryService';
import { storageAdapter } from '@/lib/storageAdapter';

const names = [
  'Cover loaded successfully', 'Drawing loaded successfully', 'Drawing resolution adequate', 'Drawing cleaned',
  'Minimum line thickness', 'Minimum feature size', 'Artwork within decoration zone',
  'No overlap with protected zones', 'Minimum wall thickness passed', 'Attachment geometry preserved',
  'Ossiguard area preserved', 'Required SHiRE logo present', 'Geometry service connected',
  'Real geometry generated', 'Manifold mesh passed', 'Final export available'
];
const icons = { pass: CheckCircle2, warning: AlertTriangle, fail: XCircle, not_checked: Clock3, simulation_only: Clock3 };

const groups = [
  ['Cover integrity', ['Cover loaded successfully']],
  ['Artwork quality', ['Drawing loaded successfully', 'Drawing resolution adequate', 'Drawing cleaned', 'Minimum line thickness', 'Minimum feature size', 'Artwork within decoration zone']],
  ['Prosthetic clearance', ['No overlap with protected zones', 'Minimum wall thickness passed']],
  ['Connector preservation', ['Attachment geometry preserved', 'Ossiguard area preserved']],
  ['Manufacturing readiness', ['Geometry service connected', 'Real geometry generated', 'Manifold mesh passed', 'Final export available']],
  ['SHiRE compliance', ['Required SHiRE logo present']]
];

const friendlyGroups = [
  { label: 'Design quality', checks: ['Drawing loaded successfully', 'Drawing resolution adequate', 'Drawing cleaned', 'Minimum line thickness', 'Minimum feature size', 'Artwork within decoration zone'] },
  { label: 'Cover safety', checks: ['Cover loaded successfully', 'No overlap with protected zones', 'Minimum wall thickness passed'] },
  { label: 'Branding', checks: ['Required SHiRE logo present'] },
  { label: '3D processing', checks: ['Geometry service connected', 'Real geometry generated', 'Manifold mesh passed', 'Final export available'] }
];

const friendly = {
  'Cover loaded successfully': { what: 'A cover is selected for this design.', why: 'Artwork is placed on a real cover shape.' },
  'Drawing loaded successfully': { what: 'At least one design piece is added.', why: 'You need a design before we can check it.' },
  'Drawing resolution adequate': { what: 'The design image is clear enough.', why: 'Small images may print blurry.' },
  'Drawing cleaned': { what: 'The drawing has been prepared.', why: 'A cleaned drawing prints more reliably.' },
  'Minimum line thickness': { what: 'Lines are thick enough to print.', why: 'Very thin lines may disappear.' },
  'Minimum feature size': { what: 'Details are large enough.', why: 'Tiny details may not print clearly.' },
  'Artwork within decoration zone': { what: 'The design sits in an allowed area.', why: 'Some areas must stay clear.' },
  'No overlap with protected zones': { what: 'The design avoids protected areas.', why: 'Protected areas must stay clear for safety.' },
  'Minimum wall thickness passed': { what: 'Walls are thick enough.', why: 'Thin walls may break.' },
  'Attachment geometry preserved': { what: 'Attachment areas are untouched.', why: 'The cover must still fit the prosthetic.' },
  'Ossiguard area preserved': { what: 'The Ossiguard area is untouched.', why: 'This area must stay clear.' },
  'Required SHiRE logo present': { what: 'The SHiRE creator mark is present.', why: 'Validated designs show the SHiRE mark.' },
  'Geometry service connected': { what: '3D processing is connected.', why: 'Real geometry needs the live engine.' },
  'Real geometry generated': { what: 'Real 3D geometry has been created.', why: 'Only the engine can make printable geometry.' },
  'Manifold mesh passed': { what: 'The 3D model is closed.', why: 'An open surface cannot be printed.' },
  'Final export available': { what: 'The final file can be saved to SHiRE storage.', why: 'Export needs real geometry and verified storage.' }
};

// Friendly fix action per check (shown for warning/fail where a fix exists).
const fixAction = (name, projectId) => {
  const p = projectId ? `?project=${projectId}` : '';
  switch (name) {
    case 'Cover loaded successfully': return { label: 'Choose a cover', to: `/new-project` };
    case 'Drawing loaded successfully': return { label: 'Add a design', to: `/studio${p}` };
    case 'Drawing cleaned': return { label: 'Prepare drawing', to: `/sketch-3d${p}` };
    case 'Required SHiRE logo present': return { label: 'Add SHiRE logo', to: `/studio${p}` };
    case 'Geometry service connected': return { label: 'Reconnect 3D processing', to: `/settings` };
    case 'Final export available': return { label: 'Reconnect storage', to: `/settings` };
    default: return { label: 'Fix in Studio', to: `/studio${p}` };
  }
};

export default function Validation() {
  const projectId = new URLSearchParams(location.search).get('project');
  const navigate = useNavigate();
  const { mode } = useExperienceMode();
  const guided = mode === 'guided';
  const [checks, setChecks] = useState(names.map(name => ({ name, status: 'not_checked' })));
  const [settings, setSettings] = useState(null);
  const [busy, setBusy] = useState(false);
  const [overall, setOverall] = useState('NOT CHECKED');
  const [open, setOpen] = useState(new Set(groups.map(g => g[0])));

  useEffect(() => {
    base44.entities.SystemSettings.list(null, 1)
      .then(x => setSettings(Array.isArray(x) ? x[0] : null))
      .catch(() => setSettings(null));
  }, []);

  const run = async () => {
    setBusy(true);
    let project = null, cover = null, layers = [], assets = [];
    try {
      project = await base44.entities.CoverCanvasProject.get(projectId);
      const [l, a] = await Promise.all([
        base44.entities.ArtworkLayer.filter({ projectId }).catch(() => []),
        base44.entities.ArtworkAsset.filter({ projectId }).catch(() => [])
      ]);
      layers = Array.isArray(l) ? l : [];
      assets = Array.isArray(a) ? a : [];
      if (project?.coverModelId) { try { cover = await base44.entities.CoverModel.get(project.coverModelId); } catch { cover = null; } }
    } catch { /* project data optional for preview */ }

    // Best-effort simulation call; never used to infer a real pass.
    try { await GeometryService.validateGeometry(buildGeometryRequest({ project, cover, layers, assets })); } catch { /* offline — fine */ }

    const svcConnected = settings?.geometryServiceStatus === 'connected';
    const vaultOk = storageAdapter.canFinalize(settings);

    // Evidence (only these can be confirmed in the browser).
    const hasProject = !!project;
    const hasCover = !!(cover && cover.sourceFile);
    const visibleLayers = layers.filter(l => l.visible);
    const hasArtwork = visibleLayers.length > 0;
    const assetsForLayers = visibleLayers.map(l => assets.find(a => a.id === l.artworkAssetId));
    const hasAssets = hasArtwork && assetsForLayers.every(Boolean);
    const lowRes = assets.some(a => a?.width && a?.height && (a.width < 300 || a.height < 300));
    const needsCleanup = project?.inputMethod === 'sketch_3d';
    const cleaned = !needsCleanup || assets.some(a => a.processedFile);
    const hasShireBrand = layers.some(l => /shire/i.test(l.name || '')) || (Array.isArray(cover?.brandingZones) && cover.brandingZones.length > 0);

    const next = names.map(name => {
      switch (name) {
        case 'Cover loaded successfully':
          return { name, status: hasProject && hasCover ? 'pass' : 'fail', note: hasCover ? '' : 'No cover selected for this project.' };
        case 'Drawing loaded successfully':
          return { name, status: hasArtwork ? 'pass' : 'fail', note: hasArtwork ? '' : 'No visible design piece added yet.' };
        case 'Drawing resolution adequate':
          return { name, status: !hasArtwork ? 'not_checked' : lowRes ? 'warning' : 'pass', note: lowRes ? 'The image is small; details may print soft.' : '' };
        case 'Drawing cleaned':
          return { name, status: !needsCleanup ? 'pass' : cleaned ? 'pass' : 'warning', note: needsCleanup && !cleaned ? 'Run automatic cleanup before printing.' : '' };
        case 'Required SHiRE logo present':
          return { name, status: hasShireBrand ? 'pass' : 'fail', note: hasShireBrand ? '' : 'The SHiRE creator mark is missing.' };
        case 'Geometry service connected':
          return { name, status: svcConnected ? 'pass' : 'fail', note: svcConnected ? '' : '3D processing is not connected. You can keep designing and submit later.' };
        case 'Artwork within decoration zone':
        case 'No overlap with protected zones':
        case 'Minimum line thickness':
        case 'Minimum feature size':
        case 'Minimum wall thickness passed':
        case 'Attachment geometry preserved':
        case 'Ossiguard area preserved':
        case 'Manifold mesh passed':
          return { name, status: 'simulation_only', note: 'Confirmed by the real Geometry Engine during processing.' };
        case 'Real geometry generated':
          return { name, status: 'simulation_only', note: 'Browser preview only — real geometry is produced by the external engine.' };
        case 'Final export available':
          return { name, status: 'fail', note: 'Final export needs real geometry and verified SHiRE storage.' };
        default:
          return { name, status: 'not_checked' };
      }
    });
    setChecks(next);
    const failCount = next.filter(c => c.status === 'fail').length;
    const pending = next.filter(c => c.status === 'simulation_only' || c.status === 'not_checked' || c.status === 'warning').length;
    setOverall(failCount > 0 ? 'CANNOT CONTINUE YET' : pending > 0 ? 'NEEDS A SMALL CHANGE' : 'READY FOR REAL 3D PROCESSING');
    try {
      await base44.entities.ValidationReport.create({
        projectId, overallStatus: failCount > 0 ? 'fail' : 'simulation_only', checks: next,
        warnings: ['Preview checks are not manufacturing validation.'], failures: next.filter(c => c.status === 'fail').map(c => c.name),
        generatedDate: new Date().toISOString()
      });
    } catch { /* non-fatal */ }
    setBusy(false);
  };

  const blocked = checks.some(x => x.status === 'fail' || x.status === 'not_checked' || x.status === 'simulation_only' || x.status === 'warning') || !storageAdapter.canFinalize(settings);
  const toggle = (g) => setOpen(s => { const n = new Set(s); n.has(g) ? n.delete(g) : n.add(g); return n; });
  const checkByName = (n) => checks.find(c => c.name === n) || { status: 'not_checked' };

  const overallTone = overall === 'READY FOR REAL 3D PROCESSING' ? 'ok' : overall === 'NEEDS A SMALL CHANGE' ? 'warn' : overall === 'CANNOT CONTINUE YET' ? 'bad' : 'idle';
  const overallClass = overallTone === 'ok' ? 'text-emerald-300 border-emerald-400/40 bg-emerald-400/10'
    : overallTone === 'warn' ? 'text-amber-200 border-amber-400/40 bg-amber-400/10'
    : overallTone === 'bad' ? 'text-red-300 border-red-500/40 bg-red-500/10'
    : 'text-slate-300 border-white/10 bg-white/[0.03]';

  if (guided) {
    return (
      <>
        <PageHeader eyebrow="Check my design" title="Check my design" description="We check your design is ready. Real 3D geometry and printing checks are confirmed by the LimbForge Geometry Engine." action={<button onClick={run} disabled={busy} className="btn-secondary"><Play size={17} />{busy ? 'Checking…' : 'Run checks'}</button>} />
        <div className={`mb-6 rounded-2xl border p-5 ${overallClass}`}>
          <h2 className="font-heading text-xl font-semibold">{busy ? 'Checking your design…' : overall === 'NOT CHECKED' ? 'Not checked yet' : overall}</h2>
          <p className="mt-1 text-sm text-slate-400">{overall === 'READY FOR REAL 3D PROCESSING' ? 'Everything we can check in the browser looks good. Submit for real 3D processing to finish.' : 'Some checks need attention. Items marked Simulation require the real Geometry Engine.'}</p>
        </div>

        <div className="space-y-5">
          {friendlyGroups.map(group => {
            const groupChecks = group.checks.map(checkByName);
            const groupFail = groupChecks.some(c => c.status === 'fail');
            return (
              <section key={group.label} className="panel p-0">
                <div className="flex items-center justify-between gap-3 p-4">
                  <h3 className="text-sm font-semibold text-white">{group.label}</h3>
                  {groupFail ? <span className="rounded border border-red-500/40 bg-red-500/10 px-2 py-0.5 text-[11px] text-red-300">Needs attention</span>
                    : <span className="rounded border border-emerald-400/40 bg-emerald-400/10 px-2 py-0.5 text-[11px] text-emerald-300">Looks good</span>}
                </div>
                <div className="space-y-2 border-t border-white/[0.06] p-4">
                  {groupChecks.map(c => {
                    const Icon = icons[c.status] || Clock3;
                    const f = friendly[c.name] || { what: c.name, why: '' };
                    const needsFix = c.status === 'fail' || c.status === 'warning';
                    const fa = fixAction(c.name, projectId);
                    return (
                      <div key={c.name} className="rounded-lg border border-white/[0.06] bg-black/20 p-3">
                        <div className="flex items-center gap-3">
                          <Icon className={c.status === 'pass' ? 'text-emerald-400' : c.status === 'fail' ? 'text-red-400' : c.status === 'warning' ? 'text-amber-300' : c.status === 'simulation_only' ? 'text-cyan-300' : 'text-slate-500'} size={18} />
                          <p className="min-w-0 flex-1 text-sm font-medium text-white">{f.what}</p>
                          <StatusBadge status={c.status} />
                        </div>
                        {c.status !== 'pass' && <p className="mt-1.5 text-xs text-slate-400">{f.why}{c.note ? ` ${c.note}` : ''}</p>}
                        {needsFix && (
                          <div className="mt-2 flex flex-wrap gap-2">
                            <button onClick={() => navigate(fa.to)} className="btn-primary text-xs"><Wrench size={13} />{fa.label}</button>
                            <button onClick={() => navigate(`/studio${projectId ? `?project=${projectId}` : ''}`)} className="btn-ghost text-xs"><Eye size={13} />Show me</button>
                          </div>
                        )}
                      </div>
                    );
                  })}
                </div>
              </section>
            );
          })}
        </div>

        <div className="panel mt-6 flex flex-col items-start justify-between gap-4 md:flex-row md:items-center">
          <div>
            <h2 className="flex items-center gap-2 font-semibold text-white"><LockKeyhole size={18} className="text-amber-300" />Submit for real 3D processing</h2>
            <p className="mt-2 text-sm text-slate-400">Final geometry, printing and export are confirmed by the Geometry Engine and SHiRE storage — not by this preview.</p>
          </div>
          <button disabled={blocked} className="btn-primary"><ShieldCheck size={18} />Submit for real 3D processing</button>
        </div>
      </>
    );
  }

  return (
    <>
      <PageHeader eyebrow="Step 7 of 8 · Validation" title="Engineering inspection" description="Preview checks are separated from real geometry and safety checks. A preview never means a cover is approved." action={<button onClick={run} disabled={busy} className="btn-secondary"><Play size={17} />{busy ? 'Checking…' : 'Run checks'}</button>} />
      <div className="warning-box mb-6"><b>3D Preview — final printable geometry not yet generated.</b> Real wall, manifold, clearance and export checks require the external geometry engine and SHiREVault.</div>

      <div className="space-y-3">
        {groups.map(([label, groupNames]) => {
          const groupChecks = groupNames.map(checkByName);
          const counts = { pass: 0, warning: 0, fail: 0, not_checked: 0, simulation_only: 0 };
          groupChecks.forEach(c => counts[c.status] = (counts[c.status] || 0) + 1);
          const isOpen = open.has(label);
          return (
            <section key={label} className="panel p-0">
              <button onClick={() => toggle(label)} className="flex w-full items-center justify-between gap-3 p-4 text-left">
                <span className="flex items-center gap-3"><Activity size={16} className="text-cyan-300" /><b className="text-sm font-semibold text-white">{label}</b></span>
                <span className="flex items-center gap-3">
                  <span className="flex items-center gap-1.5 text-[11px]">
                    {counts.pass > 0 && <span className="text-emerald-300">{counts.pass} pass</span>}
                    {counts.warning > 0 && <span className="text-amber-300">{counts.warning} warn</span>}
                    {counts.fail > 0 && <span className="text-red-300">{counts.fail} fail</span>}
                    {counts.simulation_only > 0 && <span className="text-cyan-300">{counts.simulation_only} sim</span>}
                    {counts.not_checked > 0 && <span className="text-slate-500">{counts.not_checked} pending</span>}
                  </span>
                  <ChevronDown size={16} className={`text-slate-500 transition ${isOpen ? 'rotate-180' : ''}`} />
                </span>
              </button>
              {isOpen && (
                <div className="space-y-2 border-t border-white/[0.06] p-4 fade-in">
                  {groupChecks.map(c => {
                    const Icon = icons[c.status] || Clock3;
                    return (
                      <div key={c.name} className="flex items-center gap-3 rounded-lg border border-white/[0.06] bg-black/20 p-3">
                        <Icon className={c.status === 'pass' ? 'text-emerald-400' : c.status === 'fail' ? 'text-red-400' : c.status === 'warning' ? 'text-amber-300' : c.status === 'simulation_only' ? 'text-cyan-300' : 'text-slate-500'} size={18} />
                        <div className="min-w-0 flex-1"><p className="text-sm font-medium text-white">{c.name}</p>{c.note && <p className="mt-0.5 text-xs text-slate-500">{c.note}</p>}</div>
                        <StatusBadge status={c.status} />
                      </div>
                    );
                  })}
                </div>
              )}
            </section>
          );
        })}
      </div>

      <div className="panel mt-6 flex flex-col items-start justify-between gap-4 md:flex-row md:items-center">
        <div>
          <h2 className="flex items-center gap-2 font-semibold text-white"><LockKeyhole size={18} className="text-amber-300" />Print Ready approval</h2>
          <p className="mt-2 text-sm text-slate-400">Blocked while geometry is simulated, the service is unavailable, a protected zone is affected, the SHiRE logo is missing, or wall/mesh checks fail.</p>
        </div>
        <button disabled={blocked} className="btn-primary"><ShieldCheck size={18} />Approve Print Ready</button>
      </div>
    </>
  );
}