import React from 'react';
import { useQuery } from '@tanstack/react-query';
import { FolderOpen } from 'lucide-react';
import { useShireModule } from '@/context/ShireModuleContext';
import { listProjects } from '@/services/projectRepository';

export default function Projects() {
  const shire = useShireModule();
  const { data = [], isLoading, error } = useQuery({
    queryKey: ['scanforge-projects'],
    queryFn: () => listProjects({ shireClient: shire?.client, limit: 50 }),
    retry: false
  });

  return (
    <div className="mx-auto max-w-6xl">
      <p className="text-xs uppercase tracking-[.28em] text-purple-300">Local metadata library</p>
      <h2 className="mt-2 text-3xl font-semibold">Scan Projects</h2>
      {error && <div className="mt-5 rounded-xl border border-red-500/30 bg-red-500/10 p-3 text-sm text-red-200">{error.message}</div>}
      {isLoading ? <p className="mt-8 text-zinc-500">Loading projects…</p> : data.length === 0 ? (
        <div className="mt-6 rounded-2xl border border-dashed border-white/10 p-16 text-center">
          <FolderOpen className="mx-auto text-zinc-600"/><p className="mt-4 text-zinc-400">No projects created yet</p><p className="mt-1 text-sm text-zinc-600">Raw frames and meshes remain on the paired scanner; SHiRE stores verified project references and status.</p>
        </div>
      ) : (
        <div className="mt-6 grid gap-3 md:grid-cols-2 xl:grid-cols-3">{data.map((project) => (
          <article key={project.id || project.projectId} className="rounded-2xl border border-white/10 bg-[#111114] p-5">
            <p className="text-xs uppercase tracking-wider text-purple-300">{project.scan_mode?.replaceAll('_', ' ') || project.scanMode || 'Scan project'}</p>
            <h3 className="mt-2 font-semibold">{project.project_name || project.projectName || project.name}</h3>
            <p className="mt-2 line-clamp-2 text-sm text-zinc-500">{project.description || 'No description'}</p>
            <div className="mt-5 flex justify-between text-xs text-zinc-500"><span>{project.workflow_stage || project.workflowStage || 'unknown'}</span><span>{project.scale_status || project.scaleStatus || 'unscaled'}</span></div>
          </article>
        ))}</div>
      )}
    </div>
  );
}
