'use client';

import { Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useRouter, useParams } from 'next/navigation';
import SourcesPanel from '@/components/SourcesPanel';
import ChatPanel from '@/components/ChatPanel';
import StudioPanel from '@/components/StudioPanel';
import WorkspaceHeader from '@/components/WorkspaceHeader';
import SettingsModal from '@/components/SettingsModal';
import ResizableGutter from '@/components/WorkspacePanelsLayout/ResizableGutter';
import {
  DESKTOP_LAYOUT_DEFAULTS,
  type DesktopLayoutState,
  computeDesktopLayout,
  createDesktopLayoutDefaults,
  loadDesktopLayout,
  saveDesktopLayout,
} from '@/components/WorkspacePanelsLayout/layoutState';
import { WorkspaceProvider } from '@/lib/workspace';
import { getWorkspace } from '@/lib/workspaces';
import { fetchWithAuth, isAuthenticated } from '@/lib/auth';
import { useIsMobile } from '@/lib/useIsMobile';
import { useTranslation } from '@/lib/i18n';

const API = process.env.NEXT_PUBLIC_API_URL ?? '';

const COLLAPSED_WIDTH = 64;
const GUTTER_WIDTH = 10;
const SOURCES_MIN = 240;
const STUDIO_MIN = 360;
const CHAT_MIN = 60;

async function loadSession(workspaceId: string): Promise<string> {
  const res = await fetchWithAuth(`${API}/api/workspace/${encodeURIComponent(workspaceId)}/session`);
  if (!res.ok) throw new Error(`loadSession HTTP ${res.status}`);
  const { session_id } = await res.json();
  return session_id;
}

type MobileTab = 'sources' | 'chat' | 'studio';

const MOBILE_TAB_KEYS: { key: MobileTab; icon: string }[] = [
  { key: 'sources', icon: '🗂️' },
  { key: 'chat', icon: '💬' },
  { key: 'studio', icon: '📊' },
];

type Workspace = {
  id: string;
  name: string;
  isOwner?: boolean;
  canEdit?: boolean;
};

function WorkspaceContent() {
  const router = useRouter();
  const { t } = useTranslation();
  const params = useParams();
  const workspaceId = params.id as string;
  const [sessionId, setSessionId] = useState<string>('');
  const [isInitialized, setIsInitialized] = useState(false);
  const [workspace, setWorkspace] = useState<Workspace | null>(null);
  const isMobile = useIsMobile();
  const [mobileTab, setMobileTab] = useState<MobileTab>('chat');
  const [desktopLayout, setDesktopLayout] = useState<DesktopLayoutState>(DESKTOP_LAYOUT_DEFAULTS);
  const desktopRowRef = useRef<HTMLDivElement | null>(null);
  const [desktopRowWidth, setDesktopRowWidth] = useState<number>(1200);
  const [desktopRowMeasured, setDesktopRowMeasured] = useState(false);
  const [desktopLayoutLoadedWorkspaceId, setDesktopLayoutLoadedWorkspaceId] = useState<string | null>(null);
  const [settingsOpen, setSettingsOpen] = useState(false);
  const [settingsInitialSection, setSettingsInitialSection] = useState<'api-keys' | 'skills' | 'exports'>('api-keys');

  const desktopConstraints = useMemo(() => {
    return {
      containerWidth: desktopRowWidth,
      gutterWidth: GUTTER_WIDTH,
      sourcesMin: SOURCES_MIN,
      studioMin: STUDIO_MIN,
      chatMin: CHAT_MIN,
      collapsedWidth: COLLAPSED_WIDTH,
    };
  }, [desktopRowWidth]);

  useEffect(() => {
    if (!isAuthenticated()) {
      const current = window.location.pathname + window.location.search;
      router.replace(`/login?redirect=${encodeURIComponent(current)}`);
      return;
    }
    (async () => {
      const wb = await getWorkspace(workspaceId);
      if (!wb) {
        router.push('/');
        return;
      }
      setWorkspace(wb as Workspace);

      // Load or create session for this workspace from backend
      const sid = await loadSession(workspaceId);
      setSessionId(sid);

      setIsInitialized(true);
    })();
  }, [workspaceId, router]);

  useEffect(() => {
    if (isMobile) return;
    if (!desktopRowRef.current) return;
    const el = desktopRowRef.current;

    const update = () => {
      setDesktopRowWidth(el.clientWidth || 1200);
      setDesktopRowMeasured(true);
    };
    update();

    const ro = new ResizeObserver(() => update());
    ro.observe(el);
    return () => ro.disconnect();
  }, [isMobile]);

  useEffect(() => {
    if (isMobile) return;
    if (!workspaceId) return;
    if (!desktopRowMeasured) return;
    if (desktopLayoutLoadedWorkspaceId === workspaceId) return;
    const t = window.setTimeout(() => {
      const stored = loadDesktopLayout(workspaceId);
      if (stored) {
        setDesktopLayout({ ...DESKTOP_LAYOUT_DEFAULTS, ...stored });
      } else {
        setDesktopLayout(createDesktopLayoutDefaults(desktopConstraints));
      }
      setDesktopLayoutLoadedWorkspaceId(workspaceId);
    }, 0);
    return () => window.clearTimeout(t);
  }, [workspaceId, isMobile, desktopRowMeasured, desktopConstraints, desktopLayoutLoadedWorkspaceId]);

  useEffect(() => {
    if (isMobile) return;
    if (!workspaceId) return;
    if (desktopLayoutLoadedWorkspaceId !== workspaceId) return;
    const t = window.setTimeout(() => saveDesktopLayout(workspaceId, desktopLayout), 250);
    return () => window.clearTimeout(t);
  }, [workspaceId, isMobile, desktopLayout, desktopLayoutLoadedWorkspaceId]);

  const computedLayout = useMemo(() => computeDesktopLayout(desktopLayout, desktopConstraints), [desktopLayout, desktopConstraints]);

  const setDesktopLayoutNormalized = (updater: (prev: DesktopLayoutState) => DesktopLayoutState) => {
    setDesktopLayout(prev => {
      const next = updater(prev);
      const computed = computeDesktopLayout(next, desktopConstraints);
      return { ...next, sourcesWidth: computed.sourcesExpandedWidth, studioWidth: computed.studioExpandedWidth };
    });
  };

  const handleWorkspaceNameChange = useCallback((name: string) => {
    setWorkspace((prev) => (prev ? { ...prev, name } : prev));
  }, []);

  const handleTransferred = useCallback(async () => {
    // Reload workspace meta after ownership transfer
    const wb = await getWorkspace(workspaceId);
    if (wb) setWorkspace(wb as Workspace);
  }, [workspaceId]);

  const handleOpenSkillHub = () => {
    setSettingsInitialSection('skills');
    setSettingsOpen(true);
  };

  if (!isInitialized || !workspace) {
    return <div style={{ padding: '20px' }}>{t('workspacePage.loading')}</div>;
  }

  const MOBILE_TAB_LABELS: Record<MobileTab, string> = {
    sources: t('workspacePage.tabSources'),
    chat: t('workspacePage.tabChat'),
    studio: t('workspacePage.tabStudio'),
  };

  const workspaceHeader = (
    <WorkspaceHeader
      workspace={workspace}
      isOwner={workspace.isOwner !== false}
      onWorkspaceNameChange={handleWorkspaceNameChange}
      onTransferred={handleTransferred}
      onBack={() => router.push('/')}
    />
  );

  const sourcesPanel = (
    <SourcesPanel
      isOwner={workspace.isOwner !== false}
      onOpenSkillHub={handleOpenSkillHub}
    />
  );

  const chatPanel = (
    <ChatPanel
      sessionId={sessionId}
      readOnly={workspace.canEdit === false}
    />
  );

  if (isMobile) {
    return (
      <WorkspaceProvider
        workspaceId={workspaceId}
        canEdit={workspace.canEdit !== false}
        onWorkspaceNameChange={handleWorkspaceNameChange}
      >
        <div style={{ display: 'flex', flexDirection: 'column', height: '100dvh', overflow: 'hidden' }}>
          {workspaceHeader}
          {/* Panel content area */}
          <div style={{ flex: 1, overflow: 'hidden', position: 'relative' }}>
            <div style={{ display: mobileTab === 'sources' ? 'block' : 'none', position: 'absolute', inset: 0, overflow: 'auto' }}>
              {sourcesPanel}
            </div>
            <div style={{ display: mobileTab === 'chat' ? 'block' : 'none', position: 'absolute', inset: 0, overflow: 'hidden' }}>
              {chatPanel}
            </div>
            <div style={{ display: mobileTab === 'studio' ? 'block' : 'none', position: 'absolute', inset: 0, overflow: 'auto' }}>
              <StudioPanel />
            </div>
          </div>

          {/* Bottom tab bar */}
          <div style={{
            display: 'flex',
            borderTop: '1px solid #e5e7eb',
            background: '#fff',
            flexShrink: 0,
            paddingBottom: 'env(safe-area-inset-bottom, 0px)',
          }}>
            {MOBILE_TAB_KEYS.map(tab => {
              const active = mobileTab === tab.key;
              return (
                <button
                  key={tab.key}
                  onClick={() => setMobileTab(tab.key)}
                  style={{
                    flex: 1,
                    padding: '8px 0 6px',
                    background: 'none',
                    border: 'none',
                    cursor: 'pointer',
                    display: 'flex',
                    flexDirection: 'column',
                    alignItems: 'center',
                    gap: '2px',
                    color: active ? '#5c5fbc' : '#9ca3af',
                    borderTop: active ? '2px solid #5c5fbc' : '2px solid transparent',
                    transition: 'color 0.15s',
                  }}
                >
                  <span style={{ fontSize: '18px', lineHeight: 1 }}>{tab.icon}</span>
                  <span style={{ fontSize: '11px', fontWeight: active ? 600 : 400 }}>{MOBILE_TAB_LABELS[tab.key]}</span>
                </button>
              );
            })}
          </div>
        </div>
      </WorkspaceProvider>
    );
  }

  return (
    <WorkspaceProvider
      workspaceId={workspaceId}
      canEdit={workspace.canEdit !== false}
      onWorkspaceNameChange={handleWorkspaceNameChange}
    >
      {/* Full-height column: header + panels */}
      <div style={{ display: 'flex', flexDirection: 'column', height: '100vh', overflow: 'hidden', background: '#f0f2f5' }}>
        {workspaceHeader}

        {/* Three-column layout */}
        <div ref={desktopRowRef} style={{ display: 'flex', flex: 1, overflow: 'hidden', padding: '8px' }}>
          {/* Left Panel - Sources */}
          <div style={{
            width: `${computedLayout.sourcesRenderedWidth}px`,
            minWidth: `${computedLayout.sourcesRenderedWidth}px`,
            maxWidth: `${computedLayout.sourcesRenderedWidth}px`,
            height: '100%',
            overflow: 'hidden',
            borderRadius: '8px',
            boxShadow: '0 1px 3px rgba(0,0,0,0.08)',
          }}>
            <SourcesPanel
              isOwner={workspace.isOwner !== false}
              collapsed={desktopLayout.sourcesCollapsed}
              onToggleCollapsed={() => setDesktopLayoutNormalized(prev => ({ ...prev, sourcesCollapsed: !prev.sourcesCollapsed }))}
              onOpenSkillHub={handleOpenSkillHub}
            />
          </div>

          <ResizableGutter
            ariaLabel={t('workspacePage.gutterSources')}
            width={GUTTER_WIDTH}
            disabled={desktopLayout.sourcesCollapsed}
            onDragDelta={(deltaPx) => {
              setDesktopLayoutNormalized(prev => ({ ...prev, sourcesWidth: prev.sourcesWidth + deltaPx }));
            }}
          />

          {/* Middle Panel - Chat */}
          <div style={{
            flex: 1,
            minWidth: `${CHAT_MIN}px`,
            height: '100%',
            overflow: 'hidden',
            borderRadius: '8px',
            boxShadow: '0 1px 3px rgba(0,0,0,0.08)',
          }}>
            {chatPanel}
          </div>

          <ResizableGutter
            ariaLabel={t('workspacePage.gutterStudio')}
            width={GUTTER_WIDTH}
            disabled={desktopLayout.studioCollapsed}
            onDragDelta={(deltaPx) => {
              setDesktopLayoutNormalized(prev => ({ ...prev, studioWidth: prev.studioWidth - deltaPx }));
            }}
          />

          {/* Right Panel - Studio */}
          <div style={{
            width: `${computedLayout.studioRenderedWidth}px`,
            minWidth: `${computedLayout.studioRenderedWidth}px`,
            maxWidth: `${computedLayout.studioRenderedWidth}px`,
            height: '100%',
            overflow: 'hidden',
            borderRadius: '8px',
            boxShadow: '0 1px 3px rgba(0,0,0,0.08)',
          }}>
            <StudioPanel
              collapsed={desktopLayout.studioCollapsed}
              onToggleCollapsed={() => setDesktopLayoutNormalized(prev => ({ ...prev, studioCollapsed: !prev.studioCollapsed }))}
            />
          </div>
        </div>
        <SettingsModal
          open={settingsOpen}
          onClose={() => setSettingsOpen(false)}
          workspaceId={workspaceId}
          initialSection={settingsInitialSection}
        />
      </div>
    </WorkspaceProvider>
  );
}

function WorkspaceLoadingFallback() {
  const { t } = useTranslation();
  return <div style={{ padding: '20px' }}>{t('workspacePage.loadingShort')}</div>;
}

export default function WorkspacePage() {
  return (
    <Suspense fallback={<WorkspaceLoadingFallback />}>
      <WorkspaceContent />
    </Suspense>
  );
}
