import { useEffect, useState } from 'react';
import { useParams, Link } from 'react-router-dom';
import { ArrowLeft, Ruler, Sparkles, Plug, Factory, ShieldCheck, Lock } from 'lucide-react';
import PageHeader from '@/components/workshop/PageHeader';
import LoadingPanel from '@/components/workshop/LoadingPanel';
import StatusPill from '@/components/workshop/StatusPill';
import { useAccount } from '@/lib/AccountContext';
import { adapters } from '@/services/serviceConfig';

const SECTIONS = [
  { key: 'measurements', label: 'Measurements', icon: Ruler, perm: 'measurements.record', entity: 'MeasurementSession', filter: 'project_uuid' },
  { key: 'design', label: 'Design Forge', icon: Sparkles, perm: 'design.use_forge', entity: 'DesignConfiguration', filter: 'project_uuid' },
  { key: 'ossiguard', label: 'Ossiguard', icon: Plug, perm: 'components.manage_ossiguard' },
  { key: 'manufacturing', label: 'Manufacturing', icon: Factory, perm: 'mfg.update_status', entity: 'ManufacturingJob', filter: 'project_uuid' },
  { key: 'validation', label: 'Validation', icon: ShieldCheck },
];

export default function BuilderProjectDetail() {
  const { projectId } = useParams();
  const { account, hasPermission } = useAccount();
  const [project, setProject] = useState(null);
  const [data, setData] = useState({});

  useEffect(() => {
    if (!account) return;
    (async () => {
      const ps = await adapters.database.filter('CoverProject', { uuid: projectId });
      const p = ps[0];
      setProject(p);
      if (!p) return;
      const results = {};
      for (const s of SECTIONS) {
        if (s.entity && s.filter) {
          results[s.key] = await adapters.database.filter(s.entity, { [s.filter]: projectId });
        }
      }
      setData(results);
    })();
  }, [projectId, account]);

  if (!account) return <LoadingPanel label="Loading" />;
  if (!project) return <LoadingPanel label="Loading project" />;

  const assigned = accountService_canAccess(account, project.uuid);
  if (!assigned) {
    return (
      <div className="panel mx-auto mt-12 max-w-lg p-8 text-center">
        <Lock className="mx-auto h-10 w-10 text-red-400" />
        <h2 className="mt-4 text-lg font-semibold text-white">Project not assigned to you</h2>
        <p className="mt-2 text-sm text-shire-text-secondary">You can only access projects assigned to your account.</p>
        <Link to="/builder" className="btn-primary mt-4">Back to my workspace</Link>
      </div>
    );
  }

  return (
    <>
      <Link to="/builder" className="mb-4 inline-flex items-center gap-1 text-sm text-slate-400 hover:text-violet-300"><ArrowLeft className="h-4 w-4" />Back to my workspace</Link>
      <PageHeader eyebrow="Assigned Project" title={project.project_id} description={project.status} />

      <div className="grid gap-4 lg:grid-cols-2 xl:grid-cols-3">
        {SECTIONS.map(s => {
          const allowed = account.role === 'owner_admin' || account.role === 'admin' || hasPermission(s.perm);
          const Icon = s.icon;
          return (
            <section key={s.key} className={`panel p-5 ${!allowed ? 'opacity-50' : ''}`}>
              <div className="mb-3 flex items-center gap-2"><Icon className="h-5 w-5 text-violet-300" /><h2 className="text-sm font-semibold text-white">{s.label}</h2></div>
              {!allowed ? (
                <p className="flex items-center gap-1.5 text-xs text-amber-300"><Lock className="h-3.5 w-3.5" />You do not have permission for this section.</p>
              ) : s.entity ? (
                (data[s.key] || []).length === 0 ? <p className="text-sm text-shire-text-muted">No records.</p> : (
                  <ul className="space-y-1.5 text-sm">
                    {(data[s.key] || []).slice(0, 5).map(r => (
                      <li key={r.uuid} className="flex justify-between"><span className="text-slate-200">{r.workflow || r.concept_name || r.job_reference || r.status}</span>{r.status && <StatusPill tone="amber">{r.status}</StatusPill>}</li>
                    ))}
                  </ul>
                )
              ) : <p className="text-sm text-shire-text-muted">Available — access from the main workshop tools.</p>}
            </section>
          );
        })}
      </div>
    </>
  );
}

function accountService_canAccess(account, projectUuid) {
  if (account.role === 'owner_admin' || account.role === 'admin') return true;
  return (account.assigned_project_uuids || []).includes(projectUuid);
}