import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { Plus, Sparkles, Loader2 } from 'lucide-react';
import { base44 } from '@/api/base44Client';
import { useExperienceMode } from '@/lib/ExperienceMode';
import PageHeader from '@/components/app/PageHeader';
import UniversalDesignCard from '@/components/universal/UniversalDesignCard';

export default function UniversalDesigns() {
  const { mode } = useExperienceMode();
  const guided = mode === 'guided';
  const [designs, setDesigns] = useState(null);
  const [variants, setVariants] = useState([]);
  const [layers, setLayers] = useState([]);

  const load = () => {
    Promise.all([
      base44.entities.UniversalDesign.list('-updated_date', 60).catch(() => []),
      base44.entities.CoverDesignVariant.list('-updated_date', 200).catch(() => []),
      base44.entities.UniversalDesignLayer.list('-updated_date', 400).catch(() => [])
    ]).then(([d, v, l]) => {
      setDesigns(Array.isArray(d) ? d : []);
      setVariants(Array.isArray(v) ? v : []);
      setLayers(Array.isArray(l) ? l : []);
    }).catch(() => { setDesigns([]); setVariants([]); setLayers([]); });
  };
  useEffect(load, []);

  const visible = (designs || []).filter(d => !d.archived);
  const variantCountFor = (id) => variants.filter(v => v.universalDesignId === id).length;
  const pieceCountFor = (id) => layers.filter(l => l.universalDesignId === id).length;

  const duplicate = async (d) => {
    const me = await base44.auth.me().catch(() => ({ id: d.owner }));
    await base44.entities.UniversalDesign.create({
      name: `${d.name} (copy)`, owner: me.id || d.owner, description: d.description,
      sourceType: d.sourceType, status: 'saved', masterPreviewImageUrl: d.masterPreviewImageUrl,
      originalPrompt: d.originalPrompt, styleTags: d.styleTags, moodTags: d.moodTags,
      colourPalette: d.colourPalette, intendedApplicationMode: d.intendedApplicationMode,
      preferredIntensity: d.preferredIntensity, symmetryPreference: d.symmetryPreference,
      character: d.character, placementIntent: d.placementIntent, masterArtworkAssetIds: d.masterArtworkAssetIds,
      originalInspiredFlag: d.originalInspiredFlag !== false, version: 1
    });
    load();
  };
  const archive = async (d) => {
    await base44.entities.UniversalDesign.update(d.id, { archived: true, status: 'archived' });
    load();
  };

  return (
    <>
      <PageHeader
        eyebrow={guided ? 'Universal Designs' : 'Library · Universal Designs'}
        title="My Universal Designs"
        description="Create your design once. Fit it to any compatible LimbForge cover. These reusable designs are independent of any one cover."
        action={(
          <div className="flex gap-2">
            <Link to="/design-canvas" className="btn-primary"><Sparkles size={16} /> Design Canvas</Link>
            <Link to="/create-design" className="btn-secondary"><Plus size={16} /> Create a design</Link>
          </div>
        )}
      />

      {!designs ? (
        <div className="panel empty"><Loader2 className="mx-auto mb-2 animate-spin text-cyan-300" />Loading designs…</div>
      ) : visible.length === 0 ? (
        <div className="panel fade-in text-center">
          <div className="mx-auto grid h-16 w-16 place-items-center rounded-2xl border border-cyan-400/30 bg-cyan-400/10 text-cyan-200"><Sparkles size={28} /></div>
          <h2 className="mt-4 font-heading text-xl font-semibold text-white">No universal designs yet</h2>
          <p className="mx-auto mt-2 max-w-md text-sm text-slate-400">Start with an idea, image or drawing. CoverCanvas will adapt it to the cover you choose later.</p>
          <Link to="/create-design" className="btn-primary mx-auto mt-5 inline-flex"><Plus size={17} /> Create your first design</Link>
        </div>
      ) : (
        <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
          {visible.map(d => (
            <UniversalDesignCard key={d.id} design={d} variantCount={variantCountFor(d.id)} pieceCount={pieceCountFor(d.id)} onDuplicate={duplicate} onArchive={archive} />
          ))}
        </div>
      )}

      <p className="mt-6 text-center text-[11px] text-slate-600">Universal Designs are creative masters — they are never modified when you fit them to a cover.</p>
    </>
  );
}