import React, { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Tabs, Button, Spin, Skeleton, Result, Grid, Select, Layout, App } from 'antd';
import { ArrowLeftOutlined, LoadingOutlined, LockOutlined, MinusOutlined, PlusOutlined, EllipsisOutlined } from '@ant-design/icons';
import UserMenu from '../components/UserMenu';
import { useZoomState } from '../utils/zoomUtils';
import { scrollToAnchor, createCopyLinkHandler, createRefreshAdHandler } from '../utils/adUtils';
import { buildTabsFromCategories } from '../utils/tabUtils';
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 mit Custom Hook
  const { zoom, handleZoom, ZOOM_LEVELS } = useZoomState();

  // Message-Hook aus App-Kontext
  const { message } = App.useApp();

  // Handler für Ad-Aktionen mit Message-Callbacks
  const handleCopyLink = createCopyLinkHandler((msg) => message.success(msg));
  const handleRefreshAd = createRefreshAdHandler(
    (msg) => message.success(msg),
    (msg) => message.info(msg)
  );



  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, zoom, darkMode, handleCopyLink, handleRefreshAd);
  }, [tabsData, zoom, darkMode, handleCopyLink, handleRefreshAd]);



  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]);

  // Scroll zu Sprungmarke nach dem Laden
  useEffect(() => {
    if (!loading && tabs.length > 0) {
      const hash = window.location.hash.substring(1);
      scrollToAnchor(hash, 20);
    }
  }, [loading, tabs, activeKey]);

  // 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)}`);
    }
  };

  // Finde den aktuellen Tab-Content
  const activeTabContent = tabs.find(tab => tab.key === activeKey)?.children;

  return (
    <div>
      <Spin spinning={loading} indicator={<LoadingOutlined spin />} size="large" tip="Lade Projektdaten..." fullscreen />
      {!loading && (
        tabs.length > 0 ? (
          isMobile ? (
            // Mobile Darstellung mit Select und separatem Content
            <Layout>
              <Layout.Header className="mobile-project-header" style={{
                background: darkMode ? '#001f1e' : '#001f1e', // Dynamisch, falls später unterschiedliche Themes gewünscht
                color: darkMode ? '#fff' : '#fff'
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12, flex: 1 }}>
                  <Button
                    icon={<ArrowLeftOutlined style={{ color: '#001f1e' }} />}
                    onClick={() => navigate('/')}
                    size="small"
                  />
                  <Select
                    value={activeKey}
                    onChange={handleTabChange}
                    style={{ 
                      flex: 1,
                      minWidth: 120,
                      height: 26
                    }}
                    size="middle"
                    suffixIcon={<EllipsisOutlined style={{ color: '#fff' }} />}
                    options={tabs.map(tab => ({
                      value: tab.key,
                      label: tab.label
                    }))}
                  />
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                    <Button size="small" shape="circle" icon={<MinusOutlined style={{ color: '#001f1e' }} />} onClick={() => handleZoom('out')} disabled={zoom <= ZOOM_LEVELS[0]}></Button>
                    <span style={{ minWidth: 36, textAlign: 'center', fontSize: 12 }}>{Math.round(zoom * 100)}%</span>
                    <Button size="small" shape="circle" icon={<PlusOutlined style={{ color: '#001f1e' }} />} onClick={() => handleZoom('in')} disabled={zoom >= ZOOM_LEVELS[ZOOM_LEVELS.length - 1]}></Button>
                  </div>
                  <UserMenu user={user} onLogout={onLogout} darkMode={darkMode} onToggleDarkMode={onToggleDarkMode} />
                </div>
              </Layout.Header>
              <Layout.Content className="mobile-project-content" style={{ padding: '0px 16px' }}>
                {activeTabContent}
              </Layout.Content>
            </Layout>
          ) : (
            // Desktop Darstellung mit Tabs
            <Tabs 
              items={tabs}
              more={{ icon: <EllipsisOutlined />, trigger: 'click' }}
              activeKey={activeKey}
              onChange={handleTabChange}
              tabBarExtraContent={{
                left: (
                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <Button
                      icon={<ArrowLeftOutlined style={{ color: '#001f1e' }} />}
                      onClick={() => navigate('/')}
                      style={{ marginRight: projectLogo ? 12 : 0 }}
                    />
                    {projectLogo && (
                      <img
                        src={projectLogo}
                        alt="Logo"
                        style={{ height: 38, marginRight: 32, objectFit: 'contain' }}
                      />
                    )}
                  </div>
                ),
                right: (
                  <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <Button size="small" shape="circle" icon={<MinusOutlined style={{ color: '#001f1e' }} />} onClick={() => handleZoom('out')} disabled={zoom <= ZOOM_LEVELS[0]}></Button>
                      <span style={{ minWidth: 48, textAlign: 'center' }}>{Math.round(zoom * 100)}%</span>
                      <Button size="small" shape="circle" icon={<PlusOutlined style={{ color: '#001f1e' }} />} onClick={() => handleZoom('in')} disabled={zoom >= ZOOM_LEVELS[ZOOM_LEVELS.length - 1]}></Button>
                    </div>
                    <UserMenu user={user} onLogout={onLogout} darkMode={darkMode} onToggleDarkMode={onToggleDarkMode} />
                  </div>
                )
              }}
            />
          )
        ) : 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;