// src/pages/Articles.tsx
import React, { useState } from 'react';
import api from '../utils/api';
import ArticleCard from '../components/ArticleCard';
import { Article } from '../types/article';
import { capitalizeCzech, normalizeCzech } from '../utils/cz_uk';
import { useTopics } from '../contexts/TopicsContext';
import { useLocation } from 'react-router-dom';

interface ArticlesProps {
  topicFilter?: string;
}

const Articles: React.FC = (props: ArticlesProps) => {
  const location = useLocation();
  const routerState = location.state as ArticlesProps | null;

  const [difficulty, setDifficulty] = useState('');
  const [topic, setTopic] = useState(routerState?.topicFilter ? capitalizeCzech(routerState.topicFilter) : '');
  const [contentType, setContentType] = useState<'fyzicka' | 'digitalni'>('fyzicka');
  const [input, setInput] = useState('');

  const [isLoading, setIsLoading] = useState(false);
  const [articles, setArticles] = useState<Article[]>([]);

  const difficultyLevels = ['Lehká', 'Střední', 'Obtížná'];

  const { topics } = useTopics();

  // Updated mapping according to the provided types
  type subTopic = {
    id: number;
    subtopic: string;
  };

  const subTopics: subTopic[] | undefined = topics?.flatMap(topic =>
    topic.subtopics.map(t => ({
      id: Number(t.id),
      subtopic: capitalizeCzech(t.subtopic)
    }))
  );

  const buildQueryParams = () => {
    const raw = {
      difficulty: difficulty ? normalizeCzech(difficulty) : undefined,
      topic: topic ? topic.toUpperCase() : undefined,
      contentType,
      input: input || undefined,
    };
    return Object.fromEntries(
      Object.entries(raw).filter(([, v]) => v !== undefined && v !== '')
    );
  };

  const handleSubmit = async () => {
    if (isLoading) return;
    setIsLoading(true);

    try {
      const res = await api.get<{ articles: Article[] }>('/articles/all', {
        params: buildQueryParams(),
      });
      setArticles(res.data.articles);
      console.log('✅ Filtered articles', res.data);
    } catch (err: any) {
      console.error('❌ Could not fetch', err.response ?? err);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <>
      {/* Filters */}
      <div className="max-w-6xl mx-auto w-full p-6 bg-yellow-50 mb-8">
        <div className="flex flex-wrap w-full space-x-4">
          {/* Topic */}
          <div className="flex-1">
            <label htmlFor="topic" className="block text-sm font-medium text-green-950 mb-1">
              Téma
            </label>
            <select
              id="topic"
              value={topic}
              onChange={e => setTopic(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-green-800 focus:border-green-800"
            >
              <option value=""></option>
              {subTopics?.map(t => (
                <option key={t.id} value={t.subtopic}>
                  {t.subtopic}
                </option>
              ))}
            </select>
          </div>

          {/* Difficulty */}
          <div className="flex-1">
            <label htmlFor="difficulty" className="block text-sm font-medium text-green-950 mb-1">
              Obtížnost
            </label>
            <select
              id="difficulty"
              value={difficulty}
              onChange={e => setDifficulty(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-green-800 focus:border-green-800"
            >
              <option value=""></option>
              {difficultyLevels.map(level => (
                <option key={level} value={level}>
                  {level}
                </option>
              ))}
            </select>
          </div>

          {/* Content type */}
          <div className="flex-1">
            <label className="block text-sm font-medium text-green-950 mb-1">Typ obsahu</label>
            <select
              value={contentType}
              onChange={e => setContentType(e.target.value as 'fyzicka' | 'digitalni')}
              className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-green-800 focus:border-green-800"
            >
              <option value="fyzicka">Fyzický</option>
              <option value="digitalni">Digitální</option>
            </select>
          </div>

          {/* Search text */}
          <div className="flex-1">
            <label className="block text-sm font-medium text-green-950 mb-1">Hledat</label>
            <input
              type="text"
              placeholder="Hledat článek…"
              value={input}
              onChange={e => setInput(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-green-800 focus:border-green-800"
            />
          </div>

          <div className="flex-1 self-end">
            <button
              onClick={handleSubmit}
              className="bg-green-900 hover:bg-green-800 text-white px-4 py-2 rounded transition w-1/2"
            >
              {isLoading ? 'Načítám…' : 'Hledat'}
            </button>
          </div>
        </div>
      </div>

      {/* Results */}
      <div className="max-w-6xl mx-auto w-full">
        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-3 gap-6">
          {articles.map(article => (
            <div key={article.id} className="w-full">
              <ArticleCard article={article} />
            </div>
          ))}
        </div>
      </div>
    </>
  );
};

export default Articles;
