import { useState, useEffect } from 'react';
import { useParams, Link } from 'react-router-dom';
import { useRecipe } from '../hooks/useRecipe';
import { colors, radius, spacing, shadows } from '../theme';

/**
 * CookModePage - Hands-free cooking interface with wake lock
 */
export function CookModePage() {
  const { id } = useParams();
  const recipeId = id ? parseInt(id, 10) : null;
  const { recipe, loading, error } = useRecipe(recipeId);

  // Track checked ingredients and steps
  const [checkedIngredients, setCheckedIngredients] = useState<Set<number>>(new Set());
  const [checkedSteps, setCheckedSteps] = useState<Set<number>>(new Set());

  // Wake lock state
  const [wakeLock, setWakeLock] = useState<WakeLockSentinel | null>(null);
  const [wakeLockSupported, setWakeLockSupported] = useState(false);

  // Check if Wake Lock API is supported
  useEffect(() => {
    setWakeLockSupported('wakeLock' in navigator);
  }, []);

  // Request wake lock
  const requestWakeLock = async () => {
    if (!wakeLockSupported) return;
    try {
      // @ts-ignore
      const lock = await navigator.wakeLock.request('screen');
      setWakeLock(lock);
      lock.addEventListener('release', () => setWakeLock(null));
    } catch (err) { /* ignore */ }
  };

  // Release wake lock
  const releaseWakeLock = async () => {
    if (wakeLock) {
      await wakeLock.release();
      setWakeLock(null);
    }
  };
  const toggleWakeLock = () => { (wakeLock ? releaseWakeLock() : requestWakeLock()); };
  useEffect(() => () => { if (wakeLock) wakeLock.release(); }, [wakeLock]);

  const toggleIngredient = (index: number) => {
    setCheckedIngredients(prev => {
      const next = new Set(prev);
      next.has(index) ? next.delete(index) : next.add(index);
      return next;
    });
  };
  const toggleStep = (index: number) => {
    setCheckedSteps(prev => {
      const next = new Set(prev);
      next.has(index) ? next.delete(index) : next.add(index);
      return next;
    });
  };

  if (loading) {
    return (
      <div className="flex justify-center items-center min-h-[50vh]">
        <div className="text-center">
          <div className="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
          <p className="mt-4 text-gray-600">Loading recipe...</p>
        </div>
      </div>
    );
  }
  if (error || !recipe) {
    return (
      <div className="bg-red-50 border border-red-200 rounded-2xl p-8 max-w-md mx-auto shadow-card text-center">
        <h2 className="text-2xl font-bold text-red-800 mb-2">Error Loading Recipe</h2>
        <p className="text-red-600 mb-4">{error || 'Recipe not found'}</p>
        <Link to="/" className="inline-block px-4 py-2 bg-red-600 text-white rounded-full hover:bg-red-700 transition-colors shadow">Back to Recipes</Link>
      </div>
    );
  }

  // Use fallback if recipe.instructions missing
  const instructions: string[] = Array.isArray(recipe.instructions) ? recipe.instructions : recipe.steps?.map(s => s.instruction) || [];
  const ingredients = Array.isArray(recipe.ingredients) ? recipe.ingredients : [];
  const ingredientsTotal = ingredients.length;
  const stepsTotal = instructions.length;
  const ingredientsChecked = checkedIngredients.size;
  const stepsChecked = checkedSteps.size;
  const ingredientsProgress = ingredientsTotal > 0 ? (ingredientsChecked / ingredientsTotal) * 100 : 0;
  const stepsProgress = stepsTotal > 0 ? (stepsChecked / stepsTotal) * 100 : 0;

  return (
    <div className="max-w-3xl mx-auto py-7">
      <div className="bg-white rounded-2xl shadow-card p-7 mb-8 border border-gray-100">
        <div className="flex items-start justify-between mb-4 gap-6 flex-wrap">
          <div className="flex-1 min-w-0">
            <h1 className="text-3xl font-bold text-gray-900 mb-2 break-words">{recipe.title}</h1>
            {recipe.description && (<p className="text-gray-600 text-base mb-1 break-words">{recipe.description}</p>)}
          </div>
          <Link to={`/recipe/${recipe.id}`} className="ml-4 px-4 py-2 text-blue-600 hover:bg-blue-50 rounded-md border border-blue-100 transition-colors text-sm font-medium shadow-sm">Exit Cook Mode</Link>
        </div>
        <div className="flex flex-wrap gap-5 text-sm text-gray-600 mb-4">
          {recipe.servings && (<div className="bg-gray-50 rounded-md px-3 py-1 font-medium shadow-inner">Servings: <span className="ml-1">{recipe.servings}</span></div>)}
          {recipe.prep_time_minutes && (<div className="bg-gray-50 rounded-md px-3 py-1 font-medium shadow-inner">Prep: <span className="ml-1">{recipe.prep_time_minutes} min</span></div>)}
          {recipe.cook_time_minutes && (<div className="bg-gray-50 rounded-md px-3 py-1 font-medium shadow-inner">Cook: <span className="ml-1">{recipe.cook_time_minutes} min</span></div>)}
        </div>
        {wakeLockSupported && (
          <div className="border-t pt-4 mt-4">
            <button onClick={toggleWakeLock} className={`w-full sm:w-auto px-6 py-3 rounded-lg font-medium transition-colors focus:outline-none shadow ${wakeLock ? 'bg-green-600 text-white hover:bg-green-700' : 'bg-gray-200 text-gray-700 hover:bg-gray-300'}`}>
              {wakeLock ? '🔒 Screen Locked (Stay Awake)' : '🔓 Screen Will Sleep (Tap to Lock)'}
            </button>
            <p className="mt-2 text-sm text-gray-500">{wakeLock ? 'Your screen will stay on while cooking' : 'Enable to prevent your screen from turning off'}</p>
          </div> )}
      </div>
      <div className="bg-white rounded-2xl shadow-card p-7 mb-8 border border-gray-100">
        <div className="flex items-center justify-between mb-4"><h2 className="text-2xl font-bold text-gray-900">Ingredients</h2><div className="text-sm font-medium text-gray-600">{ingredientsChecked} of {ingredientsTotal}</div></div>
        <div className="mb-6 bg-gray-200 rounded-full h-2 overflow-hidden">
          <div className="bg-green-600 h-full transition-all duration-300" style={{ width: `${ingredientsProgress}%` }} />
        </div>
        <div className="space-y-3">
          {ingredients.map((ingredient: any, index: number) => (
            <label key={index} className="flex items-start gap-3 p-3 rounded-lg border border-gray-100 hover:bg-gray-50 cursor-pointer transition-colors shadow-sm">
              <input type="checkbox" checked={checkedIngredients.has(index)} onChange={() => toggleIngredient(index)} className="mt-1 h-5 w-5 rounded border-gray-300 text-blue-600 focus:ring-blue-500 cursor-pointer" />
              <span className={`text-lg flex-1 ${checkedIngredients.has(index) ? 'line-through text-gray-500' : 'text-gray-900'}`}>{'item' in ingredient ? ingredient.item : typeof ingredient === 'string' ? ingredient : ''}</span>
            </label>
          ))}
        </div>
      </div>
      <div className="bg-white rounded-2xl shadow-card p-7 mb-8 border border-gray-100">
        <div className="flex items-center justify-between mb-4"><h2 className="text-2xl font-bold text-gray-900">Instructions</h2><div className="text-sm font-medium text-gray-600">{stepsChecked} of {stepsTotal}</div></div>
        <div className="mb-6 bg-gray-200 rounded-full h-2 overflow-hidden"><div className="bg-blue-600 h-full transition-all duration-300" style={{ width: `${stepsProgress}%` }} /></div>
        <div className="space-y-4">
          {instructions.map((instruction, index) => (
            <label key={index} className="flex items-start gap-4 p-4 border border-gray-100 rounded-xl hover:bg-gray-50 cursor-pointer transition-colors shadow-sm">
              <div className="flex items-center gap-3">
                <div className={`flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center font-bold ${checkedSteps.has(index) ? 'bg-blue-600 text-white' : 'bg-gray-200 text-gray-600'}`}>{index + 1}</div>
                <input type="checkbox" checked={checkedSteps.has(index)} onChange={() => toggleStep(index)} className="h-5 w-5 rounded border-gray-300 text-blue-600 focus:ring-blue-500 cursor-pointer" />
              </div>
              <span className={`text-lg flex-1 ${checkedSteps.has(index) ? 'line-through text-gray-500' : 'text-gray-900'}`}>{instruction}</span>
            </label>
          ))}
        </div>
      </div>
      {ingredientsChecked === ingredientsTotal && stepsChecked === stepsTotal && (
        <div className="bg-green-50 border-2 border-green-500 rounded-2xl p-7 mb-8 text-center shadow-card">
          <div className="text-4xl mb-3">🎉</div>
          <h3 className="text-2xl font-bold text-green-800 mb-2">All Done!</h3>
          <p className="text-green-700 text-lg mb-4">You've completed all steps. Enjoy your meal!</p>
          <Link to={`/recipe/${recipe.id}`} className="inline-block px-6 py-3 bg-green-600 text-white rounded-full hover:bg-green-700 transition-colors font-medium shadow">Back to Recipe</Link>
        </div> )}
    </div>
  );
}
