'use client';

import type { Recipe, RecipeQuantity } from '@/lib/recipes';
import { RecipeTable } from './recipe-table';
import { BookOpen, GitBranch, Grid3X3, Printer } from 'lucide-react';
import { useEffect, useId, useState } from 'react';

type TabId = 'fiche' | 'diagramme' | 'table';

const difficultyLabels = { easy: 'Facile', medium: 'Intermédiaire', hard: 'Difficile' } as const;

function durationLabel(value: string | null | undefined) {
  if (!value) return null;
  const match = value.match(/^PT(?:(\d+)H)?(?:(\d+)M)?$/);
  if (!match) return value;
  return [match[1] ? `${match[1]} h` : '', match[2] ? `${match[2]} min` : ''].filter(Boolean).join(' ');
}

function quantityLabel(quantity: RecipeQuantity | null) {
  if (!quantity) return '';
  if (quantity.text) return quantity.text;
  const value = quantity.maxValue ? `${quantity.value}–${quantity.maxValue}` : quantity.value;
  return [value, quantity.unit].filter(Boolean).join(' ');
}

function Diagram({ chart, title }: { chart: string; title: string }) {
  const rawId = useId();
  const [svg, setSvg] = useState('');
  const [failed, setFailed] = useState(false);

  useEffect(() => {
    let active = true;
    const render = async () => {
      const mermaid = (await import('mermaid')).default;
      mermaid.initialize({
        startOnLoad: false,
        securityLevel: 'strict',
        theme: 'base',
        htmlLabels: false,
        themeVariables: { fontFamily: 'Arial, sans-serif' },
        flowchart: { curve: 'basis' },
      });
      const id = `recipe-diagram-${rawId.replace(/[^a-z0-9-]/gi, '')}`;
      const result = await mermaid.render(id, chart);
      if (active) setSvg(result.svg);
    };
    void render().catch((error: unknown) => {
      if (!active) return;
      console.error('Échec du rendu Mermaid', error);
      setFailed(true);
    });
    return () => { active = false; };
  }, [chart, rawId]);

  return (
    <div className="recipe-diagram" role="img" aria-label={`Diagramme de préparation : ${title}`}>
      {svg ? <div dangerouslySetInnerHTML={{ __html: svg }} /> : (
        <p role="status">{failed ? 'Ce diagramme ne peut pas être affiché.' : 'Chargement du diagramme…'}</p>
      )}
    </div>
  );
}

function RecipeImages({ images }: { images: Recipe['images'] }) {
  return images.map((image) => (
    <figure className="recipe-illustration" key={image.id}>
      <img src={image.src} alt={image.alt} />
    </figure>
  ));
}

function RecipeSheet({ recipe }: { recipe: Recipe }) {
  const illustrations = recipe.images.filter((image) => image.role !== 'step');
  const asideImages = illustrations.filter((image) => image.placement === 'sidebar');
  const bodyImages = illustrations.filter((image) => image.placement !== 'sidebar');
  const hasSidebar = Boolean(recipe.ingredients.length || recipe.tools.length || recipe.notes.length || asideImages.length);
  const servings = recipe.yield;
  const metadata = [
    { label: 'Catégorie', value: recipe.categoryLabel },
    { label: 'Origine', value: recipe.origin },
    { label: 'Préparation', value: durationLabel(recipe.times?.prep) },
    { label: 'Cuisson', value: durationLabel(recipe.times?.cook) },
    { label: 'Repos', value: durationLabel(recipe.times?.rest) },
    { label: 'Rendement', value: servings && `${servings.value}${servings.maxValue ? `–${servings.maxValue}` : ''} ${servings.unit === 'servings' ? 'portions' : servings.unit}` },
    { label: 'Difficulté', value: recipe.difficulty && difficultyLabels[recipe.difficulty] },
  ].filter(({ value }) => value);

  return (
    <article className={`recipe-sheet recipe-theme-${recipe.category}`}>
      <header className="recipe-sheet-header">
        <h1>{recipe.title}</h1>
        <dl className="recipe-metadata">
          {metadata.map(({ label, value }) => (
            <div key={label}><dt>{label}</dt><dd>{value}</dd></div>
          ))}
        </dl>
        <div className="recipe-tags no-print" aria-label="Tags">
          {recipe.tags.map((tag) => <span key={tag}>{tag}</span>)}
        </div>
        {recipe.metadata.sources.length > 0 && <p className="recipe-source-links">
          <strong>Source :</strong>{' '}
          {recipe.metadata.sources.map((source, index) => (
            <span key={`${index}-${source.url ?? source.label}`}>
              {index > 0 && ' · '}
              {source.url ? <a href={source.url} target="_blank" rel="noreferrer">{source.label || source.url}</a> : source.label}
            </span>
          ))}
        </p>}
      </header>

      <div className={`recipe-sheet-grid${hasSidebar ? ' has-sidebar' : ''}`}>
        <div className="recipe-method">
          {recipe.description && <p className="recipe-description">{recipe.description}</p>}
          {recipe.steps.map((group) => (
            <section key={group.id}>
              <h2>{group.name}</h2>
              <ol>
                {group.items.map((step) => (
                  <li key={step.id}>
                    <span>{step.instruction}</span>
                    {(step.duration || step.temperature) && <small>{[durationLabel(step.duration), step.temperature && `${step.temperature.value} °${step.temperature.unit}`].filter(Boolean).join(' · ')}</small>}
                    <RecipeImages images={recipe.images.filter((image) => image.role === 'step' && (step.imageRef === image.id || image.stepRef === step.id))} />
                  </li>
                ))}
              </ol>
            </section>
          ))}
          <RecipeImages images={bodyImages} />
        </div>

        {hasSidebar && <aside className="recipe-sidebar">
          {recipe.ingredients.length > 0 && <section>
            <h2>Ingrédients</h2>
            {recipe.ingredients.map((group) => (
              <div key={group.id} className="recipe-ingredient-group">
                <h3>{group.name}</h3>
                <ul>{group.items.map((ingredient) => (
                  <li key={ingredient.id}>
                    {ingredient.quantity && <strong>{quantityLabel(ingredient.quantity)} </strong>}
                    {ingredient.name}
                    {ingredient.preparation && <> <span className="recipe-annotation">({ingredient.preparation})</span></>}
                    {ingredient.optional && <span className="recipe-annotation"> · facultatif</span>}
                    {ingredient.note && <small className="recipe-annotation">{ingredient.note}</small>}
                  </li>
                ))}</ul>
              </div>
            ))}
          </section>}
          {recipe.tools.length > 0 && <section>
            <h2>Matériel</h2>
            <ul>{recipe.tools.map((tool) => <li key={tool.id}>{tool.name}{tool.optional && ' (facultatif)'}</li>)}</ul>
          </section>}
          {recipe.notes.length > 0 && <section>
            <h2>Notes</h2>
            <ul>{recipe.notes.map((note, index) => <li key={`${index}-${note}`}>{note}</li>)}</ul>
          </section>}
          <RecipeImages images={asideImages} />
        </aside>}
      </div>
    </article>
  );
}

export function PrintRecipeButton() {
  return <button className="recipe-print" type="button" onClick={() => window.print()}><Printer aria-hidden="true"/> Imprimer</button>;
}

export function RecipeTabs({ recipe }: { recipe: Recipe }) {
  const [tab, setTab] = useState<TabId>('fiche');
  const tabs: { id: TabId; label: string; icon: typeof BookOpen }[] = [
    { id: 'fiche', label: 'Fiche recette', icon: BookOpen },
    { id: 'diagramme', label: 'Diagramme', icon: GitBranch },
    { id: 'table', label: 'Table', icon: Grid3X3 },
  ];

  return (
    <div className="recipe-document">
      <div className="recipe-toolbar no-print">
        <div className="recipe-tablist" role="tablist" aria-label="Vues de la recette">
          {tabs.map(({ id, label, icon: Icon }) => (
            <button key={id} id={`tab-${id}`} type="button" role="tab" aria-selected={tab === id} aria-controls={`panel-${id}`} onClick={() => setTab(id)}>
              <Icon aria-hidden="true"/>{label}
            </button>
          ))}
        </div>
        <PrintRecipeButton />
      </div>

      <section id={`panel-${tab}`} role="tabpanel" aria-labelledby={`tab-${tab}`} className="recipe-tabpanel">
        {tab === 'fiche' && <RecipeSheet recipe={recipe}/>} 
        {tab === 'diagramme' && (
          <div className="recipe-a4-panel">
            <header><span>Flux de préparation</span><h1>{recipe.title}</h1></header>
            {recipe.diagram?.type === 'mermaid' && <Diagram chart={recipe.diagram.chart} title={recipe.title} />}
            {!recipe.diagram && <p>Aucun diagramme pour cette fiche.</p>}
          </div>
        )}
        {tab === 'table' && <RecipeTable recipe={recipe} />}
      </section>
    </div>
  );
}
