'use client';

import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Bug } from 'lucide-react';
import { useGameStore } from '@/lib/game/stores';
import { GUARDIANS, ELEMENTS } from '@/lib/game/constants';

export function PactDebug() {
  // Get state from the main game store where pacts are stored
  const store = useGameStore();
  const signedPacts = useGameStore((s) => s.signedPacts);
  const signedPactDetails = useGameStore((s) => s.signedPactDetails);
  const elements = useGameStore((s) => s.elements);
  const prestigeUpgrades = useGameStore((s) => s.prestigeUpgrades);
  
  // Get all guardian floors
  const guardianFloors = Object.keys(GUARDIANS).map(Number).sort((a, b) => a - b);

  // Helper to add log messages
  const addLog = (message: string) => {
    store.log.unshift(message);
  };

  // Force sign a pact with a guardian (bypass costs and time)
  const forcePact = (floor: number) => {
    const guardian = GUARDIANS[floor];
    if (!guardian) return;

    // Check if already signed
    if (signedPacts.includes(floor)) {
      addLog(`⚠️ Already signed pact with ${guardian.name}!`);
      return;
    }

    // Check max pacts
    const maxPacts = 1 + (prestigeUpgrades?.pactCapacity || 0);
    if (signedPacts.length >= maxPacts) {
      addLog(`⚠️ Cannot sign more pacts! Maximum: ${maxPacts}.`);
      return;
    }

    // Force sign the pact
    const newSignedPacts = [...signedPacts, floor];
    
    // Add pact details
    const newSignedPactDetails = {
      ...signedPactDetails,
      [floor]: {
        floor,
        guardianId: guardian.element,
        signedAt: { day: store.day, hour: store.hour },
        skillLevels: {} as Record<string, number>,
      },
    };

    // Unlock mana types
    let newElements = { ...elements };
    for (const elemId of guardian.unlocksMana) {
      if (newElements[elemId]) {
        newElements = {
          ...newElements,
          [elemId]: { ...newElements[elemId], unlocked: true },
        };
      }
    }

    // Check for compound element unlocks
    const unlockedSet = new Set(
      Object.entries(newElements)
        .filter(([, e]) => e.unlocked)
        .map(([id]) => id)
    );

    for (const [elemId, elemDef] of Object.entries(ELEMENTS)) {
      if (elemDef.recipe && !newElements[elemId]?.unlocked) {
        const canUnlock = elemDef.recipe.every((comp: string) => unlockedSet.has(comp));
        if (canUnlock) {
          newElements = {
            ...newElements,
            [elemId]: { ...newElements[elemId], unlocked: true },
          };
          addLog(`🔮 ${elemDef.name} mana unlocked through component synergy!`);
        }
      }
    }

    addLog(`📜 DEBUG: Pact with ${guardian.name} force-signed! ${guardian.unlocksMana.map(e => ELEMENTS[e]?.name || e).join(', ')} mana unlocked!`);

    // Update store
    store.setState({
      signedPacts: newSignedPacts,
      signedPactDetails: newSignedPactDetails,
      elements: newElements,
    });
  };

  // Remove a pact
  const removePact = (floor: number) => {
    const guardian = GUARDIANS[floor];
    const newSignedPacts = signedPacts.filter(f => f !== floor);
    const newSignedPactDetails = { ...signedPactDetails };
    delete newSignedPactDetails[floor];

    addLog(`📜 DEBUG: Removed pact with ${guardian?.name || 'Unknown'}!`);

    store.setState({
      signedPacts: newSignedPacts,
      signedPactDetails: newSignedPactDetails,
    });
  };

  // Clear all pacts
  const clearAllPacts = () => {
    addLog(`📜 DEBUG: Cleared all pacts!`);
    store.setState({
      signedPacts: [],
      signedPactDetails: {},
    });
  };

  return (
    <Card className="bg-gray-900/80 border-gray-700 md:col-span-2">
      <CardHeader className="pb-2">
        <CardTitle className="text-orange-400 text-sm flex items-center gap-2">
          <Bug className="w-4 h-4" />
          Pact Debug
        </CardTitle>
      </CardHeader>
      <CardContent>
        <div className="space-y-3">
          <p className="text-xs text-gray-400 mb-2">
            Force sign pacts with guardians (bypasses mana costs and signing time)
          </p>
          
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2">
            {guardianFloors.map((floor) => {
              const guardian = GUARDIANS[floor];
              const isSigned = signedPacts.includes(floor);
              
              return (
                <div
                  key={floor}
                  className={`p-2 rounded border flex items-center justify-between ${
                    isSigned ? 'border-green-600/50 bg-green-900/20' : 'border-gray-700'
                  }`}
                  style={{ borderColor: isSigned ? undefined : guardian.color, borderWidth: '1px' }}
                >
                  <div>
                    <div className="text-sm font-semibold" style={{ color: guardian.color }}>
                      {guardian.name}
                    </div>
                    <div className="text-xs text-gray-400">
                      Floor {floor} | {guardian.pact}x multiplier
                    </div>
                    <div className="text-xs text-gray-500">
                      Unlocks: {guardian.unlocksMana.map(e => ELEMENTS[e]?.name || e).join(', ')}
                    </div>
                  </div>
                  <div className="flex gap-1">
                    {isSigned ? (
                      <Button
                        size="sm"
                        variant="destructive"
                        onClick={() => removePact(floor)}
                        className="text-xs"
                      >
                        Remove
                      </Button>
                    ) : (
                      <Button
                        size="sm"
                        variant="default"
                        onClick={() => forcePact(floor)}
                        className="text-xs bg-amber-600 hover:bg-amber-700"
                      >
                        Force Sign
                      </Button>
                    )}
                  </div>
                </div>
              );
            })}
          </div>

          {/* Clear All Button */}
          {signedPacts.length > 0 && (
            <div className="pt-2 border-t border-gray-700">
              <Button
                size="sm"
                variant="destructive"
                onClick={clearAllPacts}
                className="w-full text-xs"
              >
                Clear All Pacts ({signedPacts.length})
              </Button>
            </div>
          )}

          {/* Status */}
          <div className="text-xs text-gray-400 pt-2 border-t border-gray-700">
            Signed Pacts: {signedPacts.length} | 
            Max Pacts: {1 + (prestigeUpgrades?.pactCapacity || 0)}
          </div>
        </div>
      </CardContent>
    </Card>
  );
}
