import React, { useState } from 'react';
import { X, Filter, Search, RotateCcw, Check, Shield, Cpu, Activity, Landmark, FileCheck, Zap, Leaf, GraduationCap, Factory, Car, ShoppingBag, Link as LinkIcon, FileText, LayoutGrid, Newspaper, Briefcase, PlayCircle, Code, Compass, HelpCircle } from 'lucide-react';
import type { TaxonomyMeta, AssetQueryFilters } from '../../../types/assets';

interface FilterDrawerProps {
  isOpen: boolean;
  onClose: () => void;
  meta: TaxonomyMeta | null;
  filters: AssetQueryFilters;
  onChangeFilters: (newFilters: AssetQueryFilters) => void;
  onClearAll: () => void;
}

const VERTICAL_ICONS: Record<string, React.ReactNode> = {
  Shield: <Shield className="w-4 h-4" />,
  Cpu: <Cpu className="w-4 h-4" />,
  Activity: <Activity className="w-4 h-4" />,
  Landmark: <Landmark className="w-4 h-4" />,
  FileCheck: <FileCheck className="w-4 h-4" />,
  Zap: <Zap className="w-4 h-4" />,
  Leaf: <Leaf className="w-4 h-4" />,
  GraduationCap: <GraduationCap className="w-4 h-4" />,
  Factory: <Factory className="w-4 h-4" />,
  Car: <Car className="w-4 h-4" />,
  ShoppingBag: <ShoppingBag className="w-4 h-4" />,
  Link: <LinkIcon className="w-4 h-4" />,
};

const CONTENT_TYPE_CONFIG: Record<string, { label: string; icon: React.ReactNode; color: string }> = {
  case_study: { label: 'Case Studies', icon: <FileText className="w-4 h-4" />, color: 'bg-emerald-500/10 text-emerald-600 border-emerald-500/20' },
  showcase: { label: 'Showcases', icon: <LayoutGrid className="w-4 h-4" />, color: 'bg-slate-500/10 text-slate-700 dark:text-slate-300 border-slate-500/20' },
  newsletter: { label: 'Newsletters', icon: <Newspaper className="w-4 h-4" />, color: 'bg-amber-500/10 text-amber-600 border-amber-500/20' },
  portfolio: { label: 'Portfolios & Decks', icon: <Briefcase className="w-4 h-4" />, color: 'bg-purple-500/10 text-purple-600 border-purple-500/20' },
  mvp: { label: 'Live MVPs', icon: <PlayCircle className="w-4 h-4" />, color: 'bg-sky-500/10 text-sky-600 border-sky-500/20' },
  document: { label: 'Documents & PDFs', icon: <FileText className="w-4 h-4" />, color: 'bg-slate-500/10 text-slate-600 border-slate-500/20' },
  workflow: { label: 'Workflow Automations', icon: <Code className="w-4 h-4" />, color: 'bg-cyan-500/10 text-cyan-600 border-cyan-500/20' },
  use_case: { label: 'Technical Use Cases', icon: <Compass className="w-4 h-4" />, color: 'bg-blue-500/10 text-blue-600 border-blue-500/20' },
  test_drive: { label: 'Test Drive Resources', icon: <HelpCircle className="w-4 h-4" />, color: 'bg-rose-500/10 text-rose-600 border-rose-500/20' },
};

export const FilterDrawer: React.FC<FilterDrawerProps> = ({
  isOpen,
  onClose,
  meta,
  filters,
  onChangeFilters,
  onClearAll,
}) => {
  const [filterQuery, setFilterQuery] = useState('');

  if (!isOpen) return null;

  const toggleArrayItem = (current: string[] | undefined, item: string): string[] => {
    const arr = current || [];
    return arr.includes(item) ? arr.filter(x => x !== item) : [...arr, item];
  };

  const activeCount =
    (filters.verticalIds?.length || 0) +
    (filters.contentTypes?.length || 0) +
    (filters.subcategories?.length || 0) +
    (filters.tags?.length || 0);

  const filteredVerticals = (meta?.verticals || []).filter(v =>
    v.name.toLowerCase().includes(filterQuery.toLowerCase())
  );

  const filteredSubcategories = (meta?.subcategories || []).filter(s =>
    s.name.toLowerCase().includes(filterQuery.toLowerCase())
  );

  const filteredTags = (meta?.tags || []).filter(t =>
    t.name.toLowerCase().includes(filterQuery.toLowerCase())
  );

  return (
    <div className="fixed inset-0 z-50 overflow-hidden">
      {/* Backdrop */}
      <div
        className="absolute inset-0 bg-slate-900/60 backdrop-blur-sm transition-opacity duration-300 animate-fadeIn"
        onClick={onClose}
      />

      <div className="fixed inset-y-0 right-0 max-w-full flex pl-10">
        <div className="w-screen max-w-md bg-white dark:bg-slate-900 shadow-2xl border-l border-slate-200 dark:border-slate-800 flex flex-col transform transition-transform duration-300">
          
          {/* Header */}
          <div className="px-6 py-5 border-b border-slate-200 dark:border-slate-800 flex items-center justify-between bg-slate-50/50 dark:bg-slate-900/50">
            <div className="flex items-center gap-3">
              <div className="p-2 rounded-lg bg-slate-100 dark:bg-slate-800 text-slate-900 dark:text-slate-100">
                <Filter className="w-5 h-5" />
              </div>
              <div>
                <h2 className="text-lg font-bold text-slate-900 dark:text-slate-100 flex items-center gap-2">
                  Asset Discovery Filters
                  {activeCount > 0 && (
                    <span className="px-2 py-0.5 text-xs font-bold rounded-full bg-slate-900 text-white dark:bg-slate-100 dark:text-slate-900">
                      {activeCount}
                    </span>
                  )}
                </h2>
                <p className="text-xs text-slate-500 dark:text-slate-400">
                  Narrow catalog by domains, types & tags
                </p>
              </div>
            </div>
            <button
              onClick={onClose}
              className="p-2 text-slate-400 hover:text-slate-600 dark:hover:text-slate-200 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800 transition-colors"
            >
              <X className="w-5 h-5" />
            </button>
          </div>

          {/* Quick Search inside Filters */}
          <div className="p-4 border-b border-slate-100 dark:border-slate-800 bg-slate-50/30 dark:bg-slate-900/30">
            <div className="relative">
              <Search className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
              <input
                type="text"
                placeholder="Search filter keywords..."
                value={filterQuery}
                onChange={e => setFilterQuery(e.target.value)}
                className="w-full pl-9 pr-4 py-2 text-xs rounded-lg border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 text-slate-900 dark:text-slate-100 placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-slate-400"
              />
            </div>
          </div>

          {/* Body Content */}
          <div className="flex-1 overflow-y-auto p-6 space-y-7 custom-scrollbar">

            {/* 1. Industry Verticals */}
            <div>
              <h3 className="text-xs font-bold uppercase tracking-wider text-slate-400 dark:text-slate-500 mb-3 flex items-center justify-between">
                <span>Industry Verticals</span>
                <span className="text-[10px] lowercase font-normal text-slate-400">
                  ({filteredVerticals.length})
                </span>
              </h3>
              <div className="space-y-1.5">
                {filteredVerticals.map(vertical => {
                  const isSelected = filters.verticalIds?.includes(vertical.id);
                  const iconNode = vertical.icon ? VERTICAL_ICONS[vertical.icon] : null;

                  return (
                    <button
                      key={vertical.id}
                      onClick={() =>
                        onChangeFilters({
                          ...filters,
                          verticalIds: toggleArrayItem(filters.verticalIds, vertical.id),
                        })
                      }
                      className={`w-full flex items-center justify-between px-3 py-2 rounded-lg text-xs font-medium transition-all ${
                        isSelected
                          ? 'bg-slate-900 text-white dark:bg-slate-100 dark:text-slate-900 font-bold shadow-sm'
                          : 'text-slate-700 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-800/60 border border-transparent'
                      }`}
                    >
                      <div className="flex items-center gap-2.5 min-w-0">
                        <span
                          className="w-2.5 h-2.5 rounded-full shrink-0"
                          style={{ backgroundColor: vertical.color || '#3b82f6' }}
                        />
                        <span className="shrink-0 opacity-80">
                          {iconNode}
                        </span>
                        <span className="truncate">{vertical.name}</span>
                      </div>
                      <div className="flex items-center gap-2 shrink-0">
                        <span className={`text-[10px] font-mono px-1.5 py-0.5 rounded ${
                          isSelected ? 'bg-white/20 text-white dark:bg-slate-800 dark:text-slate-200' : 'bg-slate-100 dark:bg-slate-800 text-slate-500'
                        }`}>
                          {vertical._count?.assets ?? 0}
                        </span>
                        <div
                          className={`w-4 h-4 rounded border flex items-center justify-center transition-colors ${
                            isSelected
                              ? 'bg-amber-500 border-amber-500 text-slate-950'
                              : 'border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800'
                          }`}
                        >
                          {isSelected && <Check className="w-3 h-3 stroke-[3]" />}
                        </div>
                      </div>
                    </button>
                  );
                })}
              </div>
            </div>

            {/* 2. Content Types */}
            <div>
              <h3 className="text-xs font-bold uppercase tracking-wider text-slate-400 dark:text-slate-500 mb-3">
                Content Types
              </h3>
              <div className="grid grid-cols-1 gap-2">
                {(meta?.contentTypes || []).map(ct => {
                  const isSelected = filters.contentTypes?.includes(ct.name);
                  const config = CONTENT_TYPE_CONFIG[ct.name] || {
                    label: ct.name,
                    icon: <FileText className="w-4 h-4" />,
                    color: 'bg-slate-100 text-slate-700',
                  };

                  return (
                    <button
                      key={ct.name}
                      onClick={() =>
                        onChangeFilters({
                          ...filters,
                          contentTypes: toggleArrayItem(filters.contentTypes, ct.name),
                        })
                      }
                      className={`flex items-center justify-between p-2.5 rounded-lg border text-xs transition-all ${
                        isSelected
                          ? 'bg-slate-900 text-white border-slate-900 shadow-sm font-bold dark:bg-slate-100 dark:text-slate-900'
                          : 'bg-white dark:bg-slate-800/80 text-slate-700 dark:text-slate-200 border-slate-200 dark:border-slate-700 hover:border-slate-400'
                      }`}
                    >
                      <div className="flex items-center gap-2.5">
                        <span>{config.icon}</span>
                        <span>{config.label}</span>
                      </div>
                      <span
                        className={`text-[10px] font-mono px-2 py-0.5 rounded-full ${
                          isSelected
                            ? 'bg-white/20 text-white dark:bg-slate-800 dark:text-slate-200'
                            : 'bg-slate-100 dark:bg-slate-700 text-slate-600 dark:text-slate-300'
                        }`}
                      >
                        {ct.count}
                      </span>
                    </button>
                  );
                })}
              </div>
            </div>

            {/* 3. Subcategories */}
            {filteredSubcategories.length > 0 && (
              <div>
                <h3 className="text-xs font-bold uppercase tracking-wider text-slate-400 dark:text-slate-500 mb-3">
                  Subcategories
                </h3>
                <div className="flex flex-wrap gap-1.5">
                  {filteredSubcategories.map(sub => {
                    const isSelected = filters.subcategories?.includes(sub.name);
                    return (
                      <button
                        key={sub.name}
                        onClick={() =>
                          onChangeFilters({
                            ...filters,
                            subcategories: toggleArrayItem(filters.subcategories, sub.name),
                          })
                        }
                        className={`px-2.5 py-1 rounded-md text-xs font-medium border transition-all ${
                          isSelected
                            ? 'bg-slate-900 text-white dark:bg-slate-100 dark:text-slate-900 border-slate-900 dark:border-slate-100 font-semibold'
                            : 'bg-slate-50 dark:bg-slate-800/60 text-slate-600 dark:text-slate-300 border-slate-200 dark:border-slate-700 hover:bg-slate-100'
                        }`}
                      >
                        {sub.name} <span className="opacity-60 text-[10px]">({sub.count})</span>
                      </button>
                    );
                  })}
                </div>
              </div>
            )}

            {/* 4. Tag Cloud */}
            {filteredTags.length > 0 && (
              <div>
                <h3 className="text-xs font-bold uppercase tracking-wider text-slate-400 dark:text-slate-500 mb-3">
                  Tags & Keywords
                </h3>
                <div className="flex flex-wrap gap-1.5">
                  {filteredTags.map(tag => {
                    const isSelected = filters.tags?.includes(tag.name);
                    return (
                      <button
                        key={tag.name}
                        onClick={() =>
                          onChangeFilters({
                            ...filters,
                            tags: toggleArrayItem(filters.tags, tag.name),
                          })
                        }
                        className={`px-2 py-0.5 rounded-full text-xs font-mono transition-all ${
                          isSelected
                            ? 'bg-slate-900 text-white font-semibold dark:bg-slate-100 dark:text-slate-900'
                            : 'bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400 hover:bg-slate-200 dark:hover:bg-slate-700'
                        }`}
                      >
                        #{tag.name} <span className="opacity-60 text-[10px]">({tag.count})</span>
                      </button>
                    );
                  })}
                </div>
              </div>
            )}

          </div>

          {/* Footer Actions */}
          <div className="p-4 border-t border-slate-200 dark:border-slate-800 bg-slate-50/80 dark:bg-slate-900/80 flex items-center justify-between gap-3">
            <button
              onClick={onClearAll}
              disabled={activeCount === 0}
              className="flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-medium text-slate-600 dark:text-slate-400 hover:text-slate-900 dark:hover:text-white disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
            >
              <RotateCcw className="w-3.5 h-3.5" />
              Clear All ({activeCount})
            </button>
            <button
              onClick={onClose}
              className="px-5 py-2 rounded-lg bg-slate-900 hover:bg-slate-800 dark:bg-slate-100 dark:hover:bg-white text-white dark:text-slate-900 text-xs font-bold shadow-md transition-all"
            >
              Apply Filters
            </button>
          </div>

        </div>
      </div>
    </div>
  );
};
