import { useState, useEffect, useMemo } from 'react';
import { Search, ChevronDown, ChevronUp, Filter, Swords, Compass, Clock, Zap } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/shared/components/ui/card';
import { Input } from '@/shared/components/ui/input';
import { Button } from '@/shared/components/ui/button';
import { ActionIcon, ActionTypeBadge } from '@/shared/components/ui/action-icon';
import { FeatDetailModal } from './feat-detail-modal';
import type { CharacterFeat } from '@/shared/types';

interface ActionResult {
  criticalSuccess?: string;
  success?: string;
  failure?: string;
  criticalFailure?: string;
}

interface Action {
  id: string;
  name: string;
  actions: number | 'reaction' | 'free' | 'varies' | null;
  actionType: 'action' | 'reaction' | 'free' | 'exploration' | 'downtime' | 'varies';
  traits: string[];
  rarity: string;
  skill?: string;
  requirements?: string;
  trigger?: string;
  description: string;
  results?: ActionResult;
}

interface ActionsData {
  actions: Action[];
}

type ActionTypeFilter = 'all' | 'action' | 'reaction' | 'free' | 'exploration' | 'downtime';

const ACTION_TYPE_CONFIG: Record<ActionTypeFilter, { label: string; icon: React.ReactNode }> = {
  all: { label: 'Alle', icon: <Swords className="h-4 w-4" /> },
  action: { label: 'Aktionen', icon: <Swords className="h-4 w-4" /> },
  reaction: { label: 'Reaktionen', icon: <Zap className="h-4 w-4" /> },
  free: { label: 'Freie', icon: <Zap className="h-4 w-4" /> },
  exploration: { label: 'Erkundung', icon: <Compass className="h-4 w-4" /> },
  downtime: { label: 'Auszeit', icon: <Clock className="h-4 w-4" /> },
};

function ActionCard({ action, isExpanded, onToggle }: { action: Action; isExpanded: boolean; onToggle: () => void }) {
  return (
    <div
      className="rounded-lg bg-bg-secondary hover:bg-bg-tertiary transition-colors cursor-pointer"
      onClick={onToggle}
    >
      <div className="flex items-center justify-between p-3">
        <div className="flex items-center gap-3 min-w-0">
          <ActionIcon actions={action.actions} size="md" />
          <div className="min-w-0">
            <span className="font-medium text-text-primary block truncate">{action.name}</span>
            {action.skill && (
              <span className="text-xs text-text-muted">{action.skill}</span>
            )}
          </div>
        </div>
        <div className="flex items-center gap-2 flex-shrink-0">
          <ActionTypeBadge type={action.actionType} />
          {isExpanded ? (
            <ChevronUp className="h-4 w-4 text-text-muted" />
          ) : (
            <ChevronDown className="h-4 w-4 text-text-muted" />
          )}
        </div>
      </div>

      {isExpanded && (
        <div className="px-3 pb-3 space-y-3 border-t border-border-primary pt-3">
          {action.traits.length > 0 && (
            <div className="flex flex-wrap gap-1">
              {action.traits.map((trait) => (
                <span
                  key={trait}
                  className="text-xs px-1.5 py-0.5 rounded bg-bg-tertiary text-text-secondary"
                >
                  {trait}
                </span>
              ))}
            </div>
          )}

          {action.trigger && (
            <div>
              <span className="text-xs font-medium text-text-secondary">Auslöser: </span>
              <span className="text-sm text-text-primary">{action.trigger}</span>
            </div>
          )}

          {action.requirements && (
            <div>
              <span className="text-xs font-medium text-text-secondary">Voraussetzungen: </span>
              <span className="text-sm text-text-primary">{action.requirements}</span>
            </div>
          )}

          <p className="text-sm text-text-primary leading-relaxed">{action.description}</p>

          {action.results && (
            <div className="space-y-1.5 pt-2 border-t border-border-primary">
              {action.results.criticalSuccess && (
                <div>
                  <span className="text-xs font-medium text-green-400">Kritischer Erfolg: </span>
                  <span className="text-sm text-text-primary">{action.results.criticalSuccess}</span>
                </div>
              )}
              {action.results.success && (
                <div>
                  <span className="text-xs font-medium text-blue-400">Erfolg: </span>
                  <span className="text-sm text-text-primary">{action.results.success}</span>
                </div>
              )}
              {action.results.failure && (
                <div>
                  <span className="text-xs font-medium text-orange-400">Fehlschlag: </span>
                  <span className="text-sm text-text-primary">{action.results.failure}</span>
                </div>
              )}
              {action.results.criticalFailure && (
                <div>
                  <span className="text-xs font-medium text-red-400">Kritischer Fehlschlag: </span>
                  <span className="text-sm text-text-primary">{action.results.criticalFailure}</span>
                </div>
              )}
            </div>
          )}
        </div>
      )}
    </div>
  );
}

interface ActionsTabProps {
  characterFeats?: CharacterFeat[];
}

type CategoryKey = 'class' | 'action' | 'reaction' | 'free' | 'exploration' | 'downtime' | 'varies';

function CollapsibleCategory({
  title,
  icon,
  count,
  isExpanded,
  onToggle,
  children,
}: {
  title: string;
  icon: React.ReactNode;
  count: number;
  isExpanded: boolean;
  onToggle: () => void;
  children: React.ReactNode;
}) {
  return (
    <Card>
      <CardHeader
        className="pb-2 cursor-pointer hover:bg-bg-secondary/50 transition-colors"
        onClick={onToggle}
      >
        <CardTitle className="text-base flex items-center justify-between">
          <div className="flex items-center gap-2">
            {icon}
            {title} ({count})
          </div>
          {isExpanded ? (
            <ChevronUp className="h-4 w-4 text-text-muted" />
          ) : (
            <ChevronDown className="h-4 w-4 text-text-muted" />
          )}
        </CardTitle>
      </CardHeader>
      {isExpanded && <CardContent className="pt-0">{children}</CardContent>}
    </Card>
  );
}

export function ActionsTab({ characterFeats = [] }: ActionsTabProps) {
  const [actions, setActions] = useState<Action[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [typeFilter, setTypeFilter] = useState<ActionTypeFilter>('all');
  const [expandedActionId, setExpandedActionId] = useState<string | null>(null);
  const [showFilters, setShowFilters] = useState(false);
  const [expandedCategories, setExpandedCategories] = useState<Set<CategoryKey>>(new Set());
  const [selectedFeat, setSelectedFeat] = useState<CharacterFeat | null>(null);

  const toggleCategory = (category: CategoryKey) => {
    setExpandedCategories((prev) => {
      const next = new Set(prev);
      if (next.has(category)) {
        next.delete(category);
      } else {
        next.add(category);
      }
      return next;
    });
  };

  useEffect(() => {
    fetch('/data/actions_german.json')
      .then((res) => res.json())
      .then((data: ActionsData) => {
        setActions(data.actions);
        setLoading(false);
      })
      .catch((err) => {
        console.error('Failed to load actions:', err);
        setLoading(false);
      });
  }, []);

  const filteredActions = useMemo(() => {
    return actions.filter((action) => {
      // Type filter
      if (typeFilter !== 'all') {
        if (typeFilter === 'free' && action.actionType !== 'free' && action.actions !== 'free') {
          return false;
        }
        if (typeFilter !== 'free' && action.actionType !== typeFilter) {
          return false;
        }
      }

      // Search filter
      if (searchQuery) {
        const query = searchQuery.toLowerCase();
        return (
          action.name.toLowerCase().includes(query) ||
          action.description.toLowerCase().includes(query) ||
          action.skill?.toLowerCase().includes(query) ||
          action.traits.some((t) => t.toLowerCase().includes(query))
        );
      }

      return true;
    });
  }, [actions, searchQuery, typeFilter]);

  const groupedActions = useMemo(() => {
    const groups: Record<string, Action[]> = {
      action: [],
      reaction: [],
      free: [],
      exploration: [],
      downtime: [],
      varies: [],
    };

    filteredActions.forEach((action) => {
      const type = action.actionType;
      if (groups[type]) {
        groups[type].push(action);
      }
    });

    return groups;
  }, [filteredActions]);

  const handleToggleAction = (actionId: string) => {
    setExpandedActionId(expandedActionId === actionId ? null : actionId);
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-48">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-500" />
      </div>
    );
  }

  const classFeats = characterFeats.filter((f) => f.source === 'CLASS');

  return (
    <div className="space-y-4">
      {/* Search and Filter */}
      <Card>
        <CardContent className="p-3">
          <div className="flex gap-2">
            <div className="relative flex-1">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-text-muted" />
              <Input
                placeholder="Aktion suchen..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-9"
              />
            </div>
            <Button
              variant={showFilters ? 'default' : 'outline'}
              size="icon"
              onClick={() => setShowFilters(!showFilters)}
            >
              <Filter className="h-4 w-4" />
            </Button>
          </div>

          {showFilters && (
            <div className="flex flex-wrap gap-2 mt-3 pt-3 border-t border-border-primary">
              {(Object.keys(ACTION_TYPE_CONFIG) as ActionTypeFilter[]).map((type) => (
                <Button
                  key={type}
                  variant={typeFilter === type ? 'default' : 'outline'}
                  size="sm"
                  onClick={() => setTypeFilter(type)}
                  className="flex items-center gap-1.5"
                >
                  {ACTION_TYPE_CONFIG[type].icon}
                  {ACTION_TYPE_CONFIG[type].label}
                </Button>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      {/* Results count */}
      <p className="text-sm text-text-muted px-1">
        {filteredActions.length} {filteredActions.length === 1 ? 'Aktion' : 'Aktionen'} gefunden
      </p>

      {/* Class Actions from Feats */}
      {classFeats.length > 0 && typeFilter === 'all' && !searchQuery && (
        <CollapsibleCategory
          title="Klassenaktionen"
          icon={<Swords className="h-4 w-4" />}
          count={classFeats.length}
          isExpanded={expandedCategories.has('class')}
          onToggle={() => toggleCategory('class')}
        >
          <div className="space-y-2">
            {classFeats.map((feat) => (
              <div
                key={feat.id}
                className="p-3 rounded-lg bg-bg-secondary hover:bg-bg-tertiary cursor-pointer"
                onClick={() => setSelectedFeat(feat)}
              >
                <span className="font-medium text-text-primary">
                  {feat.nameGerman || feat.name}
                </span>
              </div>
            ))}
          </div>
        </CollapsibleCategory>
      )}

      {/* Grouped Actions */}
      {typeFilter === 'all' ? (
        <>
          {groupedActions.action.length > 0 && (
            <CollapsibleCategory
              title="Aktionen"
              icon={<Swords className="h-4 w-4" />}
              count={groupedActions.action.length}
              isExpanded={expandedCategories.has('action')}
              onToggle={() => toggleCategory('action')}
            >
              <div className="space-y-2">
                {groupedActions.action.map((action) => (
                  <ActionCard
                    key={action.id}
                    action={action}
                    isExpanded={expandedActionId === action.id}
                    onToggle={() => handleToggleAction(action.id)}
                  />
                ))}
              </div>
            </CollapsibleCategory>
          )}

          {groupedActions.reaction.length > 0 && (
            <CollapsibleCategory
              title="Reaktionen"
              icon={<Zap className="h-4 w-4" />}
              count={groupedActions.reaction.length}
              isExpanded={expandedCategories.has('reaction')}
              onToggle={() => toggleCategory('reaction')}
            >
              <div className="space-y-2">
                {groupedActions.reaction.map((action) => (
                  <ActionCard
                    key={action.id}
                    action={action}
                    isExpanded={expandedActionId === action.id}
                    onToggle={() => handleToggleAction(action.id)}
                  />
                ))}
              </div>
            </CollapsibleCategory>
          )}

          {groupedActions.free.length > 0 && (
            <CollapsibleCategory
              title="Freie Aktionen"
              icon={<Zap className="h-4 w-4" />}
              count={groupedActions.free.length}
              isExpanded={expandedCategories.has('free')}
              onToggle={() => toggleCategory('free')}
            >
              <div className="space-y-2">
                {groupedActions.free.map((action) => (
                  <ActionCard
                    key={action.id}
                    action={action}
                    isExpanded={expandedActionId === action.id}
                    onToggle={() => handleToggleAction(action.id)}
                  />
                ))}
              </div>
            </CollapsibleCategory>
          )}

          {groupedActions.exploration.length > 0 && (
            <CollapsibleCategory
              title="Erkundungsaktivitäten"
              icon={<Compass className="h-4 w-4" />}
              count={groupedActions.exploration.length}
              isExpanded={expandedCategories.has('exploration')}
              onToggle={() => toggleCategory('exploration')}
            >
              <div className="space-y-2">
                {groupedActions.exploration.map((action) => (
                  <ActionCard
                    key={action.id}
                    action={action}
                    isExpanded={expandedActionId === action.id}
                    onToggle={() => handleToggleAction(action.id)}
                  />
                ))}
              </div>
            </CollapsibleCategory>
          )}

          {groupedActions.downtime.length > 0 && (
            <CollapsibleCategory
              title="Auszeitaktivitäten"
              icon={<Clock className="h-4 w-4" />}
              count={groupedActions.downtime.length}
              isExpanded={expandedCategories.has('downtime')}
              onToggle={() => toggleCategory('downtime')}
            >
              <div className="space-y-2">
                {groupedActions.downtime.map((action) => (
                  <ActionCard
                    key={action.id}
                    action={action}
                    isExpanded={expandedActionId === action.id}
                    onToggle={() => handleToggleAction(action.id)}
                  />
                ))}
              </div>
            </CollapsibleCategory>
          )}

          {groupedActions.varies.length > 0 && (
            <CollapsibleCategory
              title="Sonstige"
              icon={<Swords className="h-4 w-4" />}
              count={groupedActions.varies.length}
              isExpanded={expandedCategories.has('varies')}
              onToggle={() => toggleCategory('varies')}
            >
              <div className="space-y-2">
                {groupedActions.varies.map((action) => (
                  <ActionCard
                    key={action.id}
                    action={action}
                    isExpanded={expandedActionId === action.id}
                    onToggle={() => handleToggleAction(action.id)}
                  />
                ))}
              </div>
            </CollapsibleCategory>
          )}
        </>
      ) : (
        /* Flat list when filtered */
        <Card>
          <CardContent className="p-3">
            <div className="space-y-2">
              {filteredActions.length === 0 ? (
                <p className="text-center text-text-muted py-8">Keine Aktionen gefunden</p>
              ) : (
                filteredActions.map((action) => (
                  <ActionCard
                    key={action.id}
                    action={action}
                    isExpanded={expandedActionId === action.id}
                    onToggle={() => handleToggleAction(action.id)}
                  />
                ))
              )}
            </div>
          </CardContent>
        </Card>
      )}

      {/* Feat Detail Modal */}
      {selectedFeat && (
        <FeatDetailModal
          feat={selectedFeat}
          onClose={() => setSelectedFeat(null)}
          onRemove={() => {
            // No remove functionality in actions tab - just close
            setSelectedFeat(null);
          }}
        />
      )}
    </div>
  );
}
