'use client';

import { useState, useMemo } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
  Library,
  Search,
  ChevronRight,
  Layers,
  Zap,
  Star,
  X,
  Settings2,
  ArrowRight,
} from 'lucide-react';
import {
  TEMPLATES,
  TEMPLATE_CATEGORIES,
  DFTemplate,
  TemplateCategory,
} from '@/lib/dark-factory/templates';
import type { TargetLanguage, TargetDatabase } from '@/lib/dark-factory/types/generation-options';

interface TemplateLibraryProps {
  onSelectTemplate: (template: DFTemplate) => void;
  onClose: () => void;
}

const DIFFICULTY_COLORS = {
  starter: 'bg-green-500/15 text-green-400 border-green-500/30',
  intermediate: 'bg-yellow-500/15 text-yellow-400 border-yellow-500/30',
  advanced: 'bg-red-500/15 text-red-400 border-red-500/30',
};

export function TemplateLibrary({ onSelectTemplate, onClose }: TemplateLibraryProps) {
  const [search, setSearch] = useState('');
  const [selectedCategory, setSelectedCategory] = useState<TemplateCategory | 'all'>('all');
  const [previewTemplate, setPreviewTemplate] = useState<DFTemplate | null>(null);

  const filtered = useMemo(() => {
    let list = TEMPLATES;
    if (selectedCategory !== 'all') {
      list = list.filter(t => t.category === selectedCategory);
    }
    if (search.trim()) {
      const q = search.toLowerCase();
      list = list.filter(
        t =>
          t.name.toLowerCase().includes(q) ||
          t.description.toLowerCase().includes(q) ||
          t.tags.some(tag => tag.toLowerCase().includes(q))
      );
    }
    return list;
  }, [search, selectedCategory]);

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-sm p-4"
      onClick={onClose}
    >
      <motion.div
        initial={{ scale: 0.95, opacity: 0 }}
        animate={{ scale: 1, opacity: 1 }}
        exit={{ scale: 0.95, opacity: 0 }}
        className="bg-brand-bg-elevated border border-brand-deep/30 rounded-2xl max-w-5xl w-full max-h-[85vh] flex flex-col shadow-2xl"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b border-white/10">
          <div className="flex items-center gap-3">
            <Library className="w-6 h-6 text-brand" />
            <h2 className="text-2xl font-bold text-white">Template Library</h2>
            <span className="px-2 py-0.5 rounded-full bg-brand-deep/15 text-brand text-xs border border-brand-deep/30">
              {TEMPLATES.length} templates
            </span>
          </div>
          <button
            onClick={onClose}
            className="p-2 rounded-lg hover:bg-white/10 transition-colors"
          >
            <X className="w-5 h-5 text-gray-400" />
          </button>
        </div>

        {/* Search + Category Filters */}
        <div className="px-6 py-4 border-b border-white/10 space-y-3">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
            <input
              type="text"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder="Search templates by name, description, or tag..."
              className="w-full pl-10 pr-4 py-2.5 rounded-xl bg-white/5 border border-white/10 text-white placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-brand-deep/50"
            />
          </div>
          <div className="flex flex-wrap gap-2">
            <button
              onClick={() => setSelectedCategory('all')}
              className={`px-3 py-1.5 rounded-lg text-sm transition-all border ${
                selectedCategory === 'all'
                  ? 'bg-brand-deep/20 border-brand-deep/40 text-brand'
                  : 'bg-white/5 border-white/10 text-gray-400 hover:text-white hover:border-white/20'
              }`}
            >
              All
            </button>
            {TEMPLATE_CATEGORIES.map((cat) => (
              <button
                key={cat.id}
                onClick={() => setSelectedCategory(cat.id)}
                className={`px-3 py-1.5 rounded-lg text-sm transition-all border ${
                  selectedCategory === cat.id
                    ? 'bg-brand-deep/20 border-brand-deep/40 text-brand'
                    : 'bg-white/5 border-white/10 text-gray-400 hover:text-white hover:border-white/20'
                }`}
              >
                <span className="mr-1">{cat.icon}</span>
                {cat.label}
              </button>
            ))}
          </div>
        </div>

        {/* Template Grid */}
        <div className="flex-1 overflow-y-auto p-6">
          {previewTemplate ? (
            <TemplatePreview
              template={previewTemplate}
              onBack={() => setPreviewTemplate(null)}
              onUse={() => {
                onSelectTemplate(previewTemplate);
                onClose();
              }}
            />
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
              {filtered.length === 0 ? (
                <div className="col-span-full text-center py-12">
                  <Search className="w-10 h-10 text-gray-600 mx-auto mb-3" />
                  <p className="text-gray-400">No templates match your search</p>
                </div>
              ) : (
                filtered.map((template) => (
                  <TemplateCard
                    key={template.id}
                    template={template}
                    onPreview={() => setPreviewTemplate(template)}
                    onUse={() => {
                      onSelectTemplate(template);
                      onClose();
                    }}
                  />
                ))
              )}
            </div>
          )}
        </div>
      </motion.div>
    </motion.div>
  );
}

function TemplateCard({
  template,
  onPreview,
  onUse,
}: {
  template: DFTemplate;
  onPreview: () => void;
  onUse: () => void;
}) {
  return (
    <motion.div
      whileHover={{ scale: 1.02 }}
      className="group relative p-4 rounded-xl bg-white/5 border border-white/10 hover:border-brand-deep/30 transition-all cursor-pointer"
      onClick={onPreview}
    >
      <div className="flex items-start justify-between mb-3">
        <span className="text-2xl">{template.icon}</span>
        <span className={`px-2 py-0.5 rounded-full text-xs border ${DIFFICULTY_COLORS[template.difficulty]}`}>
          {template.difficulty}
        </span>
      </div>
      <h3 className="text-lg font-semibold text-white mb-1 group-hover:text-brand-light transition-colors">
        {template.name}
      </h3>
      <p className="text-sm text-gray-400 mb-3 line-clamp-2">{template.description}</p>
      <div className="flex flex-wrap gap-1.5 mb-3">
        {template.tags.slice(0, 3).map((tag) => (
          <span
            key={tag}
            className="px-2 py-0.5 rounded bg-white/5 text-gray-500 text-xs"
          >
            {tag}
          </span>
        ))}
        {template.tags.length > 3 && (
          <span className="px-2 py-0.5 rounded bg-white/5 text-gray-500 text-xs">
            +{template.tags.length - 3}
          </span>
        )}
      </div>
      <div className="flex items-center justify-between">
        <span className="text-xs text-gray-500">
          ~{template.estimatedArtifacts} artifacts
        </span>
        <button
          onClick={(e) => {
            e.stopPropagation();
            onUse();
          }}
          className="flex items-center gap-1 px-3 py-1.5 rounded-lg bg-brand-deep/15 text-brand text-sm hover:bg-brand-deep/25 transition-colors opacity-0 group-hover:opacity-100"
        >
          Use <ArrowRight className="w-3.5 h-3.5" />
        </button>
      </div>
    </motion.div>
  );
}

function TemplatePreview({
  template,
  onBack,
  onUse,
}: {
  template: DFTemplate;
  onBack: () => void;
  onUse: () => void;
}) {
  return (
    <div>
      <button
        onClick={onBack}
        className="flex items-center gap-2 text-gray-400 hover:text-white mb-4 transition-colors"
      >
        <ChevronRight className="w-4 h-4 rotate-180" />
        Back to library
      </button>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Left: Details */}
        <div>
          <div className="flex items-center gap-3 mb-4">
            <span className="text-4xl">{template.icon}</span>
            <div>
              <h3 className="text-2xl font-bold text-white">{template.name}</h3>
              <div className="flex items-center gap-2 mt-1">
                <span className={`px-2 py-0.5 rounded-full text-xs border ${DIFFICULTY_COLORS[template.difficulty]}`}>
                  {template.difficulty}
                </span>
                <span className="text-xs text-gray-500">~{template.estimatedArtifacts} artifacts</span>
              </div>
            </div>
          </div>
          <p className="text-gray-300 mb-4">{template.description}</p>
          <div className="flex flex-wrap gap-2 mb-6">
            {template.tags.map((tag) => (
              <span key={tag} className="px-2 py-1 rounded-lg bg-white/5 text-gray-400 text-sm border border-white/10">
                {tag}
              </span>
            ))}
          </div>

          {template.expertSpec && (
            <div className="space-y-3">
              <h4 className="text-sm font-medium text-gray-300 flex items-center gap-2">
                <Layers className="w-4 h-4 text-brand-secondary-light" />
                Pre-configured Entities
              </h4>
              {template.expertSpec.entities.map((entity) => (
                <div key={entity.name} className="p-3 rounded-lg bg-white/5 border border-white/10">
                  <div className="font-medium text-white text-sm">{entity.name}</div>
                  <div className="text-xs text-gray-500 mt-1">{entity.description}</div>
                  <div className="text-xs text-gray-600 mt-1">
                    {entity.fields.length} fields · {entity.relations.length} relations
                  </div>
                </div>
              ))}
            </div>
          )}

          {template.expertSpec && template.expertSpec.endpoints.length > 0 && (
            <div className="mt-4 space-y-3">
              <h4 className="text-sm font-medium text-gray-300 flex items-center gap-2">
                <Zap className="w-4 h-4 text-brand" />
                Pre-configured Endpoints
              </h4>
              {template.expertSpec.endpoints.map((ep, i) => (
                <div key={i} className="flex items-center gap-2 text-sm">
                  <span className="px-2 py-0.5 rounded bg-brand-deep/15 text-brand text-xs font-mono">
                    {ep.method}
                  </span>
                  <span className="text-gray-300 font-mono text-xs">{ep.path}</span>
                  <span className="text-gray-500 text-xs">{ep.description}</span>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Right: Prompt Preview */}
        <div>
          <h4 className="text-sm font-medium text-gray-300 mb-3">Generation Prompt</h4>
          <div className="p-4 rounded-xl bg-white/5 border border-white/10 mb-6">
            <pre className="text-sm text-gray-300 whitespace-pre-wrap">{template.prompt}</pre>
          </div>

          {template.suggestedLanguage && (
            <div className="flex items-center gap-2 mb-2 text-sm">
              <span className="text-gray-500">Suggested language:</span>
              <span className="px-2 py-0.5 rounded bg-brand-deep/10 text-brand">
                {template.suggestedLanguage}
              </span>
            </div>
          )}
          {template.suggestedDatabase && (
            <div className="flex items-center gap-2 mb-6 text-sm">
              <span className="text-gray-500">Suggested database:</span>
              <span className="px-2 py-0.5 rounded bg-brand-secondary/10 text-brand-secondary-light">
                {template.suggestedDatabase}
              </span>
            </div>
          )}

          <button
            onClick={onUse}
            className="w-full flex items-center justify-center gap-2 px-6 py-3 rounded-xl font-semibold text-white bg-gradient-to-r from-brand-deep to-brand-secondary hover:from-brand hover:to-brand-secondary-light transition-all shadow-lg shadow-brand-deep/25"
          >
            <Zap className="w-5 h-5" />
            Use This Template
          </button>

          {template.expertSpec && (
            <p className="text-xs text-gray-500 text-center mt-3 flex items-center justify-center gap-1">
              <Settings2 className="w-3 h-3" />
              This template includes an Expert Mode spec you can edit before generating
            </p>
          )}
        </div>
      </div>
    </div>
  );
}
