import { useState, useEffect } from 'react';
import { useParams, Link } from 'react-router-dom';
import { useRecipe } from '../hooks/useRecipe';
import { UiBadge, UiButton, UiPage, UiSection } from '../components/ui/primitives';

/**
 * 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);

  const [checkedIngredients, setCheckedIngredients] = useState<Set<number>>(new Set());
  const [checkedSteps, setCheckedSteps] = useState<Set<number>>(new Set());

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

  useEffect(() => {
    setWakeLockSupported('wakeLock' in navigator);
  }, []);

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

  const releaseWakeLock = async () => {
    if (wakeLock) {
      await wakeLock.release();
      setWakeLock(null);
    }
  };

  const toggleWakeLock = () => {
    wakeLock ? releaseWakeLock() : requestWakeLock();
  };

  useEffect(() => {
    return () => {
      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 (
      <UiPage className="flex min-h-[50vh] items-center justify-center">
        <div className="text-center">
          <div className="inline-block h-12 w-12 animate-spin rounded-full border-b-2 border-[var(--color-primary)]"></div>
          <p className="mt-4 text-[var(--text-dim)]">Loading recipe...</p>
        </div>
      </UiPage>
    );
  }

  if (error || !recipe) {
    return (
      <UiPage className="mx-auto max-w-md py-8">
        <UiSection className="border-[var(--danger-border)] bg-[var(--danger-bg)] text-center">
          <h2 className="mb-2 text-2xl font-bold text-[var(--danger-text)]">Error Loading Recipe</h2>
          <p className="mb-4 text-[var(--danger-text)]/90">{error || 'Recipe not found'}</p>
          <Link to="/" className="ui-btn ui-btn-secondary border-[var(--danger-border)] bg-white text-[var(--danger-text)] hover:bg-white/90">Back to Recipes</Link>
        </UiSection>
      </UiPage>
    );
  }

  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;

  const done = ingredientsChecked === ingredientsTotal && stepsChecked === stepsTotal;

  return (
    <UiPage className="mx-auto max-w-3xl py-7">
      <UiSection className="mb-8" padding="lg">
        <div className="mb-4 flex flex-wrap items-start justify-between gap-6">
          <div className="min-w-0 flex-1">
            <h1 className="mb-2 break-words text-3xl font-bold text-[var(--text-h)]">{recipe.title}</h1>
            {recipe.description && <p className="mb-1 break-words text-base text-[var(--text-dim)]">{recipe.description}</p>}
          </div>
          <Link to={`/recipe/${recipe.id}`} className="ui-btn ui-btn-secondary text-sm font-medium">Exit Cook Mode</Link>
        </div>

        <div className="mb-4 flex flex-wrap gap-3 text-sm">
          {recipe.servings && <UiBadge>Servings: {recipe.servings}</UiBadge>}
          {recipe.prep_time_minutes && <UiBadge>Prep: {recipe.prep_time_minutes} min</UiBadge>}
          {recipe.cook_time_minutes && <UiBadge>Cook: {recipe.cook_time_minutes} min</UiBadge>}
        </div>

        {wakeLockSupported && (
          <div className="mt-4 border-t border-[var(--border)] pt-4">
            <UiButton
              onClick={toggleWakeLock}
              variant={wakeLock ? 'primary' : 'secondary'}
              className={wakeLock ? '' : 'text-[var(--text-dim)]'}
            >
              {wakeLock ? '🔒 Screen Locked (Stay Awake)' : '🔓 Screen Will Sleep (Tap to Lock)'}
            </UiButton>
            <p className="mt-2 text-sm text-[var(--text-muted)]">
              {wakeLock ? 'Your screen will stay on while cooking' : 'Enable to prevent your screen from turning off'}
            </p>
          </div>
        )}
      </UiSection>

      <UiSection className="mb-8" padding="lg">
        <div className="mb-4 flex items-center justify-between">
          <h2 className="text-2xl font-bold text-[var(--text-h)]">Ingredients</h2>
          <div className="text-sm font-medium text-[var(--text-dim)]">{ingredientsChecked} of {ingredientsTotal}</div>
        </div>

        <div className="mb-6 h-2 overflow-hidden rounded-full bg-[var(--border)]">
          <div className="h-full bg-[var(--success)] transition-all duration-300" style={{ width: `${ingredientsProgress}%` }} />
        </div>

        <div className="space-y-3">
          {ingredients.map((ingredient: any, index: number) => (
            <label
              key={index}
              className="flex cursor-pointer items-start gap-3 rounded-xl border border-[var(--border)] bg-white p-3 transition-colors hover:bg-[var(--surface-muted)]"
            >
              <input
                type="checkbox"
                checked={checkedIngredients.has(index)}
                onChange={() => toggleIngredient(index)}
                className="mt-1 h-5 w-5 cursor-pointer rounded border-[var(--border-strong)] text-[var(--color-primary)] focus:ring-[var(--focus-ring)]"
              />
              <span
                className={`flex-1 text-lg ${checkedIngredients.has(index) ? 'text-[var(--text-muted)] line-through' : 'text-[var(--text)]'}`}
              >
                {'item' in ingredient ? ingredient.item : typeof ingredient === 'string' ? ingredient : ''}
              </span>
            </label>
          ))}
        </div>
      </UiSection>

      <UiSection className="mb-8" padding="lg">
        <div className="mb-4 flex items-center justify-between">
          <h2 className="text-2xl font-bold text-[var(--text-h)]">Instructions</h2>
          <div className="text-sm font-medium text-[var(--text-dim)]">{stepsChecked} of {stepsTotal}</div>
        </div>

        <div className="mb-6 h-2 overflow-hidden rounded-full bg-[var(--border)]">
          <div className="h-full bg-[var(--color-primary)] transition-all duration-300" style={{ width: `${stepsProgress}%` }} />
        </div>

        <div className="space-y-4">
          {instructions.map((instruction, index) => (
            <label
              key={index}
              className="flex cursor-pointer items-start gap-4 rounded-xl border border-[var(--border)] bg-white p-4 transition-colors hover:bg-[var(--surface-muted)]"
            >
              <div className="flex items-center gap-3">
                <div
                  className={`flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full font-bold ${
                    checkedSteps.has(index)
                      ? 'bg-[var(--color-primary)] text-white'
                      : 'bg-[var(--surface-muted)] text-[var(--text-dim)]'
                  }`}
                >
                  {index + 1}
                </div>
                <input
                  type="checkbox"
                  checked={checkedSteps.has(index)}
                  onChange={() => toggleStep(index)}
                  className="h-5 w-5 cursor-pointer rounded border-[var(--border-strong)] text-[var(--color-primary)] focus:ring-[var(--focus-ring)]"
                />
              </div>
              <span className={`flex-1 text-lg ${checkedSteps.has(index) ? 'text-[var(--text-muted)] line-through' : 'text-[var(--text)]'}`}>
                {instruction}
              </span>
            </label>
          ))}
        </div>
      </UiSection>

      {done && (
        <UiSection className="mb-8 border-[var(--success-border)] bg-[var(--success-bg)] text-center" padding="lg">
          <div className="mb-3 text-4xl">🎉</div>
          <h3 className="mb-2 text-2xl font-bold text-[var(--success-text)]">All Done!</h3>
          <p className="mb-4 text-lg text-[var(--success-text)]/90">You've completed all steps. Enjoy your meal!</p>
          <Link to={`/recipe/${recipe.id}`} className="ui-btn ui-btn-primary">Back to Recipe</Link>
        </UiSection>
      )}
    </UiPage>
  );
}
