"use client";

import { useState, useCallback, useMemo } from 'react';
import { cn } from '@/lib/utils';
import { ChessIcon } from './ChessIcon';
import { Button } from '@/components/ui/button';
import { RefreshCw, Lightbulb } from 'lucide-react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { pieceMap } from '../shared/Helpers';

type Piece = string | null;
type Board = Piece[][];
type Position = { row: number, col: number };

const createBoardFromFen = (fen: string): Board => {
  const board: Board = Array(8).fill(null).map(() => Array(8).fill(null));
  const [placement] = fen.split(' ');
  let row = 0;
  let col = 0;
  for (const char of placement) {
    if (char === '/') {
      row++;
      col = 0;
    } else if (/\d/.test(char)) {
      col += parseInt(char, 10);
    } else {
      const isWhite = char === char.toUpperCase();
      const pieceType = char.toLowerCase();
      board[row][col] = (isWhite ? 'w' : 'b') + pieceType;
      col++;
    }
  }
  return board;
};

const puzzles = [
  {
    fen: '4r2b/5R2/p5p1/1p4P1/1P2p3/2P2P1k/1P3B2/5K2 w KQkq - 0 1',
    solution: { from: { row: 1, col: 5 }, to: { row: 1, col: 7 } },
    description: "MOJ1 White to move, Mate in 1. Find the crushing blow!",
  },
  {
    fen: 'q6k/3r1p1p/1Rp2p2/2PpB3/3P4/r4P2/P5RP/1K6 w - - 0 14',
    solution: { from: { row: 3, col: 4 }, to: { row: 2, col: 5 } },
    description: "White to move, Mate in 1. Find the crushing blow!",
  },
  {
    fen: 'k7/p3q3/2p5/2Pp4/3P4/2K1P2Q/8/8 w - - 0 24',
    solution: { from: { row: 5, col: 7 }, to: { row: 0, col: 2 } },
    description: "White to move. Find the fork.",
  },
  {
    fen: '6k1/5ppp/8/8/7q/8/5PPP/4Q1K1 w - - 2 46',
    solution: { from: { row: 7, col: 4 }, to: { row: 0, col: 4 } },
    description: "White to move. Save the draw.",
  },
  {
    fen: 'r6k/2p2ppp/6q1/6N1/1p1b1P2/1P4P1/2P5/1K2R2Q w - - 2 46',
    solution: { from: { row: 7, col: 7 }, to: { row: 0, col: 0 } },
    description: "White to move. Save the draw.",
  }
];

export function TacticsTrainer() {
  const [puzzleIndex, setPuzzleIndex] = useState(0);
  const puzzle = useMemo(() => puzzles[puzzleIndex], [puzzleIndex]);

  const [board, setBoard] = useState<Board>(() => createBoardFromFen(puzzle.fen));
  const [selectedPiece, setSelectedPiece] = useState<Position | null>(null);
  const [message, setMessage] = useState<string | null>(null);
  const [isSolved, setIsSolved] = useState(false);
  const [isWrong, setIsWrong] = useState(false);

  const loadPuzzle = useCallback((index: number) => {
    const newPuzzle = puzzles[index];
    setBoard(createBoardFromFen(newPuzzle.fen));
    setSelectedPiece(null);
    setMessage(null);
    setIsSolved(false);
    setIsWrong(false);
  }, []);

  const loadNextPuzzle = () => {
    const nextIndex = (puzzleIndex + 1) % puzzles.length;
    setPuzzleIndex(nextIndex);
    loadPuzzle(nextIndex);
  };
  
  const resetPuzzle = () => {
    loadPuzzle(puzzleIndex);
  }

  const showSolution = () => {
    const newBoard = board.map(r => [...r]);
    const { from, to } = puzzle.solution;
    newBoard[to.row][to.col] = newBoard[from.row][from.col];
    newBoard[from.row][from.col] = null;
    setBoard(newBoard);
    setMessage("Solution shown.");
    setIsSolved(true);
    setIsWrong(false);
  };

  const handleSquareClick = useCallback((row: number, col: number) => {
    if (isSolved) return;

    if (selectedPiece) {
      if (row === puzzle.solution.to.row && col === puzzle.solution.to.col && selectedPiece.row === puzzle.solution.from.row && selectedPiece.col === puzzle.solution.from.col) {
         const newBoard = board.map(r => [...r]);
         newBoard[row][col] = newBoard[selectedPiece.row][selectedPiece.col];
         newBoard[selectedPiece.row][selectedPiece.col] = null;
         setBoard(newBoard);
         setMessage("Correct! Well done.");
         setIsSolved(true);
         setIsWrong(false);
         setSelectedPiece(null);
      } else {
        setMessage("Not quite. Try again!");
        setIsWrong(true);
        setSelectedPiece(null);
      }
    } else if (board[row][col]) {
      setSelectedPiece({ row, col });
      setMessage(null);
      setIsWrong(false);
    }
  }, [selectedPiece, board, isSolved, puzzle.solution]);

  return (
    <div className="flex flex-col md:flex-row gap-8 items-center justify-center">
      <div className="w-full max-w-md md:max-w-xl">
        <div className="grid grid-cols-8 aspect-square shadow-2xl rounded-lg overflow-hidden border-4 border-primary/50">
          {board.map((rowArr, rowIndex) =>
            rowArr.map((piece, colIndex) => {
              const isLightSquare = (rowIndex + colIndex) % 2 !== 0;
              const isSelected = selectedPiece && selectedPiece.row === rowIndex && selectedPiece.col === colIndex;
              
              return (
                <div
                  key={`${rowIndex}-${colIndex}`}
                  onClick={() => handleSquareClick(rowIndex, colIndex)}
                  className={cn(
                    'flex items-center justify-center aspect-square cursor-pointer transition-colors',
                    isLightSquare ? 'bg-[#64676E]' : 'bg-white',
                    isSelected && 'bg-accent/50',
                  )}
                >
                  {piece && 
                    <div className={cn('transition-transform duration-100 ease-in-out', isSolved ? '' : (isSelected ? 'scale-125' : ''))}>
                      <ChessIcon
                        piece={piece}
                        className="w-10 h-10 md:w-12 md:h-12 drop-shadow-md" 
                        alt="White King"
                        width={45}
                        height={45}
                        src={pieceMap(piece)}
                      />
                    </div>
                  }
                </div>
              );
            })
          )}
        </div>
      </div>
      <Card className="w-full max-w-md">
        <CardHeader>
          <CardTitle>Tactics Puzzle #{puzzleIndex + 1}</CardTitle>
          <CardDescription>{puzzle.description}</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          {message && (
            <div className={cn(
                "p-3 rounded-md text-center font-semibold", 
                isSolved ? "bg-green-500/20 text-green-700 dark:text-green-400" : "",
                isWrong ? "bg-destructive/20 text-destructive" : ""
            )}>
              {message}
            </div>
          )}
          <div className="grid grid-cols-2 gap-2">
            <Button onClick={showSolution} variant="outline" disabled={isSolved}>
              <Lightbulb className="mr-2 h-4 w-4" />
              Solution
            </Button>
            <Button onClick={resetPuzzle} variant="outline">
              <RefreshCw className="mr-2 h-4 w-4" />
              Reset
            </Button>
          </div>
          <Button onClick={loadNextPuzzle} className="w-full bg-accent hover:bg-accent/90 text-accent-foreground">
            Next Puzzle
          </Button>
        </CardContent>
      </Card>
    </div>
  );
}
