import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { FolderKanban, Ruler, Sparkles, Factory, ShieldCheck, ListChecks } 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';

export default function BuilderWorkspace() {
  const { account } = useAccount();
  const [projects, setProjects] = useState(null);
  const [assignments, setAssignments] = useState(null);
  const [jobs, setJobs] = useState(null);

  useEffect(() => {
    if (!account) return;
    const uuids = account.assigned_project_uuids || [];
    if (uuids.length) {
      Promise.all(uuids.map(u => adapters.database.filter('CoverProject', { uuid: u }).then(r => r[0]))).then(ps => setProjects(ps.filter(Boolean)));
    } else setProjects([]);
    adapters.database.filter('ProjectAssignment', { user_id: account.user_id }).then(setAssignments);
    adapters.database.list('ManufacturingJob').then(all => setJobs(all.filter(j => uuids.includes(j.project_uuid))));
  }, [account]);

  if (!account) return <LoadingPanel label="Loading workspace" />;
  if (!projects || !assignments) return <LoadingPanel label="Loading assignments" />;

  const dueSoon = assignments.filter(a => a.due_date && new Date(a.due_date) <= new Date(Date.now() + 7 * 86400000) && a.status !== 'Complete');
  const blocked = assignments.filter(a => a.status === 'Blocked');

  return (
    <>
      <PageHeader eyebrow={`Welcome, ${account.preferred_name || account.display_name}`} title="Builder Workspace"
        description="You only see projects and tasks assigned to you. Unrelated customers and projects are hidden." />

      <div className="mb-6 grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        <div className="panel p-5"><FolderKanban className="h-6 w-6 text-violet-300" /><p className="mt-2 text-2xl font-bold text-white">{projects.length}</p><p className="text-xs text-shire-text-muted">Assigned Projects</p></div>
        <div className="panel p-5"><ListChecks className="h-6 w-6 text-amber-300" /><p className="mt-2 text-2xl font-bold text-white">{assignments.length}</p><p className="text-xs text-shire-text-muted">Active Tasks</p></div>
        <div className="panel p-5"><ShieldCheck className="h-6 w-6 text-red-300" /><p className="mt-2 text-2xl font-bold text-white">{blocked.length}</p><p className="text-xs text-shire-text-muted">Blocked Items</p></div>
        <div className="panel p-5"><Factory className="h-6 w-6 text-emerald-300" /><p className="mt-2 text-2xl font-bold text-white">{jobs.length}</p><p className="text-xs text-shire-text-muted">Manufacturing Jobs</p></div>
      </div>

      <section className="panel mb-6 p-5">
        <h2 className="section-title">My Assigned Projects</h2>
        {projects.length === 0 ? <p className="text-sm text-shire-text-muted">No projects assigned to you yet.</p> : (
          <div className="grid gap-3 sm:grid-cols-2">
            {projects.map(p => (
              <Link key={p.uuid} to={`/builder/projects/${p.uuid}`} className="flex items-center justify-between rounded-xl border border-shire-border bg-shire-raised px-4 py-3 hover:border-shire-purple/40">
                <div><div className="text-sm font-medium text-slate-200">{p.project_id}</div><div className="text-xs text-shire-text-muted">{p.status}</div></div>
                <StatusPill tone={p.status === 'Complete' ? 'green' : 'amber'}>{p.status}</StatusPill>
              </Link>
            ))}
          </div>
        )}
      </section>

      <section className="panel p-5">
        <h2 className="section-title">Tasks Assigned to Me</h2>
        {assignments.length === 0 ? <p className="text-sm text-shire-text-muted">No tasks assigned.</p> : (
          <div className="space-y-2">
            {assignments.map(a => (
              <div key={a.uuid} className="flex items-center justify-between rounded-xl border border-shire-border bg-shire-raised px-4 py-3 text-sm">
                <div className="flex items-center gap-3">
                  {a.assignment_type === 'measurement' ? <Ruler className="h-4 w-4 text-violet-300" /> : a.assignment_type === 'design' ? <Sparkles className="h-4 w-4 text-violet-300" /> : a.assignment_type === 'manufacturing' || a.assignment_type === 'inspection' ? <Factory className="h-4 w-4 text-violet-300" /> : <ListChecks className="h-4 w-4 text-violet-300" />}
                  <div><span className="text-slate-200">{a.project_id}</span><span className="ml-2 text-xs text-shire-text-muted">{a.assignment_type.replace('_', ' ')}</span></div>
                </div>
                <div className="flex items-center gap-3">
                  {a.due_date && <span className="text-xs text-amber-300">due {new Date(a.due_date).toLocaleDateString()}</span>}
                  <StatusPill tone={a.status === 'Complete' ? 'green' : a.status === 'Blocked' ? 'red' : 'amber'}>{a.status}</StatusPill>
                </div>
              </div>
            ))}
          </div>
        )}
      </section>
    </>
  );
}