import React, { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Tabs, Button, Spin, Skeleton, Result, Grid } from 'antd';
import { ArrowLeftOutlined, LoadingOutlined, LockOutlined } from '@ant-design/icons';
import UserMenu from '../components/UserMenu';
import FilePreview, { formatFileSize, formatDuration } from '../components/FilePreview';
import debugLogger from '../utils/debugLogger';

const backendUrl = process.env.REACT_APP_BACKEND || '';
const { useBreakpoint } = Grid;

function ProjectDetail({ user, darkMode, onLogout, onToggleDarkMode, overrideParams, ...props }) {
  // URL-Parameter holen, mit Override-Support für Smart Resolution
  const routeParams = useParams();
  const params = overrideParams || routeParams;
  const { client: routeClient, project, tab } = params;
  const client = user.role === 'admin' ? routeClient : user.client;
  const navigate = useNavigate();

  // Responsive breakpoints
  const screens = useBreakpoint();
  const isMobile = !screens.md; // md breakpoint ist 768px

  debugLogger.routing('ProjectDetail - Received params:', {
    routeParams,
    overrideParams,
    finalParams: params,
    extractedValues: { client, project, tab }
  });

  // State für Fehlerstatus
  const [error, setError] = useState(null);

  // Hole Projekt-Logo (und ggf. weitere Metadaten)
  const [projectLogo, setProjectLogo] = useState(null);

  // Zoom-Logik (muss im Component-Scope stehen, nicht in useEffect!)
  const ZOOM_LEVELS = [0.15, 0.25, 0.5, 0.75, 1];
  const [zoom, setZoom] = useState(() => {
    const z = parseFloat(localStorage.getItem('adsZoom') || '1');
    return ZOOM_LEVELS.includes(z) ? z : 1;
  });
  function handleZoom(dir) {
    setZoom(z => {
      const idx = ZOOM_LEVELS.indexOf(z);
      let next = z;
      if (dir === 'in') next = ZOOM_LEVELS[Math.min(ZOOM_LEVELS.length - 1, idx + 1)];
      if (dir === 'out') next = ZOOM_LEVELS[Math.max(0, idx - 1)];
      localStorage.setItem('adsZoom', next);
      return next;
    });
  }

  useEffect(() => {
    async function fetchLogo() {
      if (!client || !project) {
        setProjectLogo(null);
        return;
      }
      try {
        const token = localStorage.getItem('jwt');
        const res = await fetch(`${backendUrl}/api/projects/${encodeURIComponent(client)}/${encodeURIComponent(project)}`, {
          headers: {
            'Authorization': 'Bearer ' + token
          }
        });
        const data = await res.json();
        if (data && data.success) {
          const { logo } = data.data;
          if (logo) setProjectLogo(logo);
        }
      } catch (e) {
        setProjectLogo(null);
      }
    }
    fetchLogo();
  }, [client, project]);

  // Tabs-Logik: Kategorien aus API laden
  const [tabsData, setTabsData] = useState(null);
  const [activeKey, setActiveKey] = useState(tab);
  const [loading, setLoading] = useState(true);

  // Tabs mit useMemo erstellen, damit sie sich bei Zoom-Änderung aktualisieren ohne API-Call
  const tabs = React.useMemo(() => {
    if (!tabsData) return [];
    return buildTabsFromCategories(tabsData);
  }, [tabsData, zoom]);

  function buildTabsFromCategories(data) {
    let categories = [];
    if (Array.isArray(data)) {
      categories = data.filter(child => child.type === 'category');
    } else if (data && Array.isArray(data.children)) {
      categories = data.children.filter(child => child.type === 'category');
    }
    return categories.map(cat => ({
      key: cat.title,
      label: cat.title,
      children: (
        <div>
          {Array.isArray(cat.children) && cat.children.filter(sub => sub.type === 'subcategory').length > 0 ? (
            cat.children.filter(sub => sub.type === 'subcategory').map(sub => (
              <div key={sub.name} style={{ marginTop: 24 }}>
                <h2 style={{ marginBottom: 4 }}>{sub.name}</h2>
                {/* Ads unterhalb der Subcategory anzeigen */}
                {Array.isArray(sub.children) && sub.children.filter(ad => ad.type === 'ad').length > 0 ? (
                  sub.children.filter(ad => ad.type === 'ad').map(ad => (
                    <div key={ad.name} style={{ marginLeft: 0, marginBottom: 16 }}>
                      <div style={{ color: '#555', fontSize: 15, display: 'flex', alignItems: 'center', gap: 8 }}>{ad.name}</div>
                      {/* Dateien unterhalb des Ads anzeigen */}
                      {Array.isArray(ad.files) && ad.files.length > 0 ? (
                        <div style={{ marginLeft: 0, display: 'flex', flexWrap: 'wrap', gap: 32 }}>
                          {ad.files.map(file => (
                            <FilePreview key={file.name + '__' + zoom} file={file} zoom={zoom} darkMode={darkMode} />
                          ))}
                        </div>
                      ) : (
                        <div style={{ color: '#bbb', marginLeft: 16, fontSize: 13 }}>Keine Dateien vorhanden.</div>
                      )}
                    </div>
                  ))
                ) : (
                  <div style={{ color: '#aaa', marginLeft: 16, fontSize: 14 }}>Keine Ads vorhanden.</div>
                )}
              </div>
            ))
          ) : (
            <div style={{ color: '#888', marginTop: 16 }}>Keine Subkategorien vorhanden.</div>
          )}
        </div>
      )
    }));
  }

  useEffect(() => {
    // Wenn Routing-Parameter fehlen, Tabs zurücksetzen
    if (!client || !project) {
      setTabsData(null);
      setActiveKey(undefined);
      setError(null);
      setLoading(false);
      return;
    }
    const cacheKey = `ads-overview-${client}-${project}`;
    const cacheTTL = 10 * 60 * 1000; // 10 Minuten
    async function fetchTabs(forceApi = false) {
      setLoading(true);
      // Prüfe Cache
      if (!forceApi) {
        const cached = localStorage.getItem(cacheKey);
        if (cached) {
          try {
            const parsed = JSON.parse(cached);
            if (parsed && parsed.data && parsed.timestamp && Date.now() - parsed.timestamp < cacheTTL) {
              // Gültiger Cache
              const data = parsed.data;
              setTabsData(data);
              const tabsArr = buildTabsFromCategories(data);
              if (tabsArr.length > 0) {
                if (tab && tabsArr.some(t => t.key === tab)) {
                  setActiveKey(tab);
                } else {
                  setActiveKey(tabsArr[0].key);
                  // Wenn Tab in URL fehlt oder ungültig, URL anpassen
                  if (!tab || !tabsArr.some(t => t.key === tab)) {
                    if (user.role === 'admin') {
                      navigate(`/${encodeURIComponent(client)}/${encodeURIComponent(project)}/${encodeURIComponent(tabsArr[0].key)}`, { replace: true });
                    } else {
                      navigate(`/${encodeURIComponent(project)}/${encodeURIComponent(tabsArr[0].key)}`, { replace: true });
                    }
                  }
                }
              }
              setLoading(false);
              return;
            }
          } catch (e) {
            // Fehler beim Parsen, ignoriere Cache und hole neu
          }
        }
      }
      // Kein Cache, abgelaufen oder Fehler: Hole neu
      try {
        setError(null); // Reset error state
        const token = localStorage.getItem('jwt');
        const res = await fetch(`${backendUrl}/api/projects/${encodeURIComponent(client)}/${encodeURIComponent(project)}/ads-overview`, {
          headers: {
            'Authorization': 'Bearer ' + token
          }
        });
        
        if (!res.ok) {
          // HTTP-Fehler behandeln
          if (res.status === 403) {
            setError({ type: 'forbidden', message: 'Keine Zugriffsberechtigung auf dieses Projekt' });
          } else if (res.status === 404) {
            setError({ type: 'notFound', message: 'Projekt wurde nicht gefunden' });
          } else {
            setError({ type: 'general', message: `Fehler beim Laden der Daten (${res.status})` });
          }
          setTabsData(null);
          setLoading(false);
          return;
        }
        
        const data = await res.json();
        // Speichere im Cache
        localStorage.setItem(cacheKey, JSON.stringify({ data, timestamp: Date.now() }));
        setTabsData(data);
        const tabsArr = buildTabsFromCategories(data);
        if (tabsArr.length > 0) {
          if (tab && tabsArr.some(t => t.key === tab)) {
            setActiveKey(tab);
          } else {
            setActiveKey(tabsArr[0].key);
            if (!tab || !tabsArr.some(t => t.key === tab)) {
              if (user.role === 'admin') {
                navigate(`/${encodeURIComponent(client)}/${encodeURIComponent(project)}/${encodeURIComponent(tabsArr[0].key)}`, { replace: true });
              } else {
                navigate(`/${encodeURIComponent(project)}/${encodeURIComponent(tabsArr[0].key)}`, { replace: true });
              }
            }
          }
        }
      } catch (e) {
        setError({ type: 'network', message: 'Netzwerkfehler beim Laden der Daten' });
        setTabsData(null);
      }
      setLoading(false);
    }
    fetchTabs();
  }, [user, client, project, tab]);

  // Tab-Wechsel: Schreibe Tab in die URL
  const handleTabChange = (key) => {
    setActiveKey(key);
    // Clients verwenden /:project/:tab, Admins /:client/:project/:tab
    if (user.role === 'admin') {
      navigate(`/${encodeURIComponent(client)}/${encodeURIComponent(project)}/${encodeURIComponent(key)}`);
    } else {
      navigate(`/${encodeURIComponent(project)}/${encodeURIComponent(key)}`);
    }
  };

  return (
    <div>
      <style>{`
        .ads-details-tabs .ant-tabs-nav {
          background: ${darkMode ? '#1f1f1f' : '#001f1e'};
          color: ${darkMode ? '#fff' : '#fff'};
          transition: background 0.2s;
        }
      `}</style>
      {/* Zoom-Buttons jetzt in tabBarExtraContent.right */}
      <Spin spinning={loading} indicator={<LoadingOutlined spin />} size="large" tip="Lade Projektdaten..." fullscreen />
      {!loading && (
        tabs.length > 0 ? (
          <Tabs
            className="ads-details-tabs"
            items={tabs}
            activeKey={activeKey}
            onChange={handleTabChange}
            tabBarExtraContent={{
              left: (
                <span style={{ display: 'flex', alignItems: 'center' }}>
                  <Button
                    icon={<ArrowLeftOutlined />}
                    onClick={() => navigate('/')}
                    style={{ marginRight: projectLogo ? 12 : 0 }}
                  />
                  {projectLogo && !isMobile && (
                    <img
                      src={projectLogo}
                      alt="Logo"
                      style={{ height: 38, marginRight: 32, objectFit: 'contain' }}
                    />
                  )}
                </span>
              ),
              right: (
                <span style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <Button size="small" onClick={() => handleZoom('out')} disabled={zoom <= ZOOM_LEVELS[0]}>-</Button>
                    <span style={{ minWidth: 48, textAlign: 'center' }}>{Math.round(zoom * 100)}%</span>
                    <Button size="small" onClick={() => handleZoom('in')} disabled={zoom >= ZOOM_LEVELS[ZOOM_LEVELS.length - 1]}>+</Button>
                  </div>
                  <UserMenu user={user} onLogout={onLogout} darkMode={darkMode} onToggleDarkMode={onToggleDarkMode} />
                </span>
              )
            }}
          />
        ) : error ? (
          // Spezifische Fehlerbehandlung
          <Result
            icon={error.type === 'forbidden' ? <LockOutlined /> : undefined}
            status={error.type === 'forbidden' ? '403' : error.type === 'notFound' ? '404' : 'error'}
            title={
              error.type === 'forbidden' ? 'Keine Zugriffsberechtigung' :
              error.type === 'notFound' ? 'Projekt nicht gefunden' : 
              'Fehler beim Laden'
            }
            subTitle={error.message}
            extra={
              <Button type="primary" onClick={() => navigate('/')}>
                {user.role === 'admin' ? 'Zurück zum Dashboard' : 'Zurück zur Übersicht'}
              </Button>
            }
          />
        ) : (
          // Fallback für andere Fälle ohne spezifischen Fehler
          <div style={{ padding: 32, textAlign: 'center', color: '#888' }}>
            <div>Keine Daten gefunden.</div>
            <Button type="primary" style={{ marginTop: 24 }} onClick={() => navigate('/')}>
              {user.role === 'admin' ? 'Zurück zum Dashboard' : 'Zurück zur Übersicht'}
            </Button>
          </div>
        )
      )}
    </div>
  );
}


export default ProjectDetail;