'use client';

import { useEffect, useRef, useState } from 'react';
import { useRouter } from 'next/navigation';
import { getWorkspaces, createWorkspace, deleteWorkspace, updateWorkspace, type Workspace } from '@/lib/workspaces';
import { fetchWithAuth, isAuthenticated, getEmail, logout } from '@/lib/auth';
import { useIsMobile } from '@/lib/useIsMobile';
import { useTranslation, type TranslationKey } from '@/lib/i18n';
import SettingsModal from '@/components/SettingsModal';
import AppHeader from '@/components/AppHeader';
const API_BASE = process.env.NEXT_PUBLIC_API_URL ?? '';
const PAGE_SIZE = 19;

// Soft, low-saturation card backgrounds — same family, low contrast between
// adjacent cards. Inspired by NotebookLM's calm palette.
const CARD_COLORS = [
  '#eef2f7', // cool light blue-grey
  '#eef0fb', // lavender mist
  '#eaf2ef', // pale mint-grey
];

// Snap a Date to local-time start-of-day.
function startOfDay(d: Date): Date {
  const out = new Date(d);
  out.setHours(0, 0, 0, 0);
  return out;
}

// Monday-anchored start-of-week in local time.
function startOfWeek(d: Date): Date {
  const out = startOfDay(d);
  const dow = (out.getDay() + 6) % 7; // 0 = Monday
  out.setDate(out.getDate() - dow);
  return out;
}

function startOfMonth(d: Date): Date {
  const out = startOfDay(d);
  out.setDate(1);
  return out;
}

function addDays(d: Date, n: number): Date {
  const out = new Date(d);
  out.setDate(out.getDate() + n);
  return out;
}

type WorkspaceGroup = { key: string; labelKey: TranslationKey; items: Workspace[] };

function groupWorkspaces(list: Workspace[], now: Date): WorkspaceGroup[] {
  const today = startOfDay(now);
  const yesterday = addDays(today, -1);
  const thisWeek = startOfWeek(now);
  const lastWeek = addDays(thisWeek, -7);
  const thisMonth = startOfMonth(now);

  const groups: WorkspaceGroup[] = [
    { key: 'today', labelKey: 'home.group.day.today', items: [] },
    { key: 'yesterday', labelKey: 'home.group.day.yesterday', items: [] },
    { key: 'earlierThisWeek', labelKey: 'home.group.day.earlierThisWeek', items: [] },
    { key: 'lastWeek', labelKey: 'home.group.day.lastWeek', items: [] },
    { key: 'earlierThisMonth', labelKey: 'home.group.day.earlierThisMonth', items: [] },
    { key: 'older', labelKey: 'home.group.day.older', items: [] },
  ];

  const byKey: Record<string, Workspace[]> = {};
  for (const g of groups) byKey[g.key] = g.items;

  for (const ws of list) {
    const t = new Date(ws.updatedAt).getTime();
    if (t >= today.getTime()) byKey.today.push(ws);
    else if (t >= yesterday.getTime()) byKey.yesterday.push(ws);
    else if (t >= thisWeek.getTime()) byKey.earlierThisWeek.push(ws);
    else if (t >= lastWeek.getTime()) byKey.lastWeek.push(ws);
    else if (t >= thisMonth.getTime()) byKey.earlierThisMonth.push(ws);
    else byKey.older.push(ws);
  }

  return groups.filter(g => g.items.length > 0);
}



// Simple workspace SVG icon
function WorkspaceIcon({ color = '#5c5fbc' }: { color?: string }) {
  return (
    <svg width="44" height="44" viewBox="0 0 44 44" fill="none">
      <rect x="8" y="4" width="28" height="36" rx="4" fill={color} fillOpacity="0.15" />
      <rect x="8" y="4" width="28" height="36" rx="4" stroke={color} strokeWidth="2" />
      <rect x="12" y="10" width="8" height="5" rx="1" fill={color} fillOpacity="0.6" />
      <rect x="22" y="10" width="10" height="2" rx="1" fill={color} fillOpacity="0.4" />
      <rect x="22" y="14" width="7" height="2" rx="1" fill={color} fillOpacity="0.4" />
      <rect x="12" y="20" width="20" height="2" rx="1" fill={color} fillOpacity="0.3" />
      <rect x="12" y="25" width="16" height="2" rx="1" fill={color} fillOpacity="0.3" />
      <rect x="12" y="30" width="18" height="2" rx="1" fill={color} fillOpacity="0.3" />
    </svg>
  );
}

// Three-dot menu
function WorkspaceMenu({ onEditTitle, onDelete, onExport }: { onEditTitle: () => void; onDelete: () => void; onExport: () => void }) {
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);
  const { t } = useTranslation();

  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
    };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, []);

  const menuItems: { key: string; label: string; color?: string; onClick: () => void }[] = [
    { key: 'edit', label: t('home.menuEditTitle'), onClick: onEditTitle },
    { key: 'export', label: t('home.menuExport'), onClick: onExport },
    { key: 'delete', label: t('home.menuDelete'), color: '#e53e3e', onClick: onDelete },
  ];

  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <button
        onClick={(e) => { e.stopPropagation(); setOpen(v => !v); }}
        style={{
          background: 'none',
          border: 'none',
          cursor: 'pointer',
          padding: '4px 6px',
          borderRadius: '6px',
          color: '#555',
          fontSize: '18px',
          lineHeight: 1,
          transition: 'background 0.15s',
        }}
        onMouseEnter={e => (e.currentTarget.style.background = 'rgba(0,0,0,0.07)')}
        onMouseLeave={e => (e.currentTarget.style.background = 'none')}
      >
        ⋮
      </button>
      {open && (
        <div style={{
          position: 'absolute',
          top: '100%',
          right: 0,
          background: '#fff',
          borderRadius: '8px',
          boxShadow: '0 4px 16px rgba(0,0,0,0.12)',
          overflow: 'hidden',
          zIndex: 100,
          minWidth: '150px',
        }}>
          {menuItems.map(item => (
            <button
              key={item.key}
              onClick={(e) => { e.stopPropagation(); setOpen(false); item.onClick(); }}
              style={{
                display: 'block',
                width: '100%',
                padding: '10px 16px',
                background: 'none',
                border: 'none',
                cursor: 'pointer',
                textAlign: 'left',
                fontSize: '14px',
                color: item.color ?? '#333',
              }}
              onMouseEnter={e => (e.currentTarget.style.background = item.color ? '#fff5f5' : '#f5f5f5')}
              onMouseLeave={e => (e.currentTarget.style.background = 'none')}
            >
              {item.label}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

export default function Home() {
  const router = useRouter();
  const { t, locale } = useTranslation();
  const [workspaces, setWorkspaces] = useState<Workspace[]>([]);
  const [totalCount, setTotalCount] = useState(0);
  const [loadingMore, setLoadingMore] = useState(false);
  const [creatingWorkspace, setCreatingWorkspace] = useState(false);
  const [hoveredId, setHoveredId] = useState<string | null>(null);
  // Edit title modal
  const [editingWorkspace, setEditingWorkspace] = useState<Workspace | null>(null);
  const [editingName, setEditingName] = useState('');
  const [deletingWorkspaceId, setDeletingWorkspaceId] = useState<string | null>(null);
  const [userEmail, setUserEmail] = useState<string | null>(null);
  const [settingsOpen, setSettingsOpen] = useState(false);
  const [settingsSection, setSettingsSection] = useState<'agent' | 'language' | 'api-keys' | 'exports'>('agent');
  const isMobile = useIsMobile();
  const creatingWorkspaceRef = useRef(false);

  const hasMore = workspaces.length < totalCount;

  const refreshWorkspaces = async () => {
    const { workspaces: wsList, total } = await getWorkspaces({ limit: PAGE_SIZE });
    setWorkspaces(wsList);
    setTotalCount(total);
  };

  const loadMore = async () => {
    setLoadingMore(true);
    try {
      const { workspaces: more, total } = await getWorkspaces({ limit: PAGE_SIZE, offset: workspaces.length });
      setWorkspaces(prev => [...prev, ...more]);
      setTotalCount(total);
    } finally {
      setLoadingMore(false);
    }
  };

  const handleLogout = async () => {
    await logout();
    router.replace('/login');
  };

  useEffect(() => {
    if (!isAuthenticated()) {
      router.replace(`/login?redirect=${encodeURIComponent(window.location.pathname + window.location.search)}`);
      return;
    }
    setUserEmail(getEmail());
    getWorkspaces({ limit: PAGE_SIZE }).then(({ workspaces: wsList, total }) => {
      setWorkspaces(wsList);
      setTotalCount(total);
    });
  }, [router]);

  const handleCreateWorkspace = async () => {
    if (creatingWorkspaceRef.current) return;

    creatingWorkspaceRef.current = true;
    setCreatingWorkspace(true);

    let created = false;
    try {
      const workspace = await createWorkspace(t('home.untitled'));
      created = true;
      router.push(`/workspace/${workspace.id}`);
    } catch (e) {
      console.error('Failed to create workspace:', e);
    } finally {
      if (!created) {
        creatingWorkspaceRef.current = false;
        setCreatingWorkspace(false);
      }
    }
  };

  const handleEditTitle = (workspace: Workspace) => {
    setEditingWorkspace(workspace);
    setEditingName(workspace.name);
  };

  const handleSaveTitle = async () => {
    if (!editingWorkspace || !editingName.trim()) return;
    await updateWorkspace(editingWorkspace.id, { name: editingName.trim() });
    await refreshWorkspaces();
    setEditingWorkspace(null);
  };

  const handleDeleteWorkspace = (id: string) => {
    setDeletingWorkspaceId(id);
  };

  const handleExportWorkspace = async (id: string) => {
    try {
      await fetchWithAuth(`${API_BASE}/api/workspace/${encodeURIComponent(id)}/export`, { method: 'POST' });
    } catch {
      // Silently ignore — the export task error will surface in the Exports panel
    }
    setSettingsSection('exports');
    setSettingsOpen(true);
  };

  const handleConfirmDelete = async () => {
    if (!deletingWorkspaceId) return;
    await deleteWorkspace(deletingWorkspaceId);
    await refreshWorkspaces();
    setDeletingWorkspaceId(null);
  };

  const formatDate = (iso: string) => {
    const d = new Date(iso);
    const tag = locale === 'zh' ? 'zh-CN' : locale === 'ja' ? 'ja-JP' : 'en-US';
    return d.toLocaleDateString(tag, { month: 'short', day: 'numeric', year: 'numeric' });
  };

  return (
    <div style={{ minHeight: '100vh', background: '#f8f9fa' }}>
      <AppHeader
        activePage="workspaces"
        email={userEmail}
        isMobile={isMobile}
        onSettings={() => { setSettingsSection('agent'); setSettingsOpen(true); }}
        onLogout={handleLogout}
      />
      <div style={{ maxWidth: '1200px', margin: '0 auto', padding: isMobile ? '24px 16px' : '40px 48px' }}>

        {/* Page title */}
        <div style={{ marginBottom: '24px' }}>
          <h1 style={{ fontSize: isMobile ? '22px' : '28px', fontWeight: 500, color: '#1a1a2e', margin: 0, letterSpacing: '-0.4px' }}>{t('home.title')}</h1>
        </div>

        {/* Grouped card sections */}
        {(() => {
          const cardHeight = isMobile ? '180px' : '220px';
          const cardPadding = isMobile ? '18px' : '22px';
          const titleSize = isMobile ? '18px' : '22px';

          const createCard = (
            <button
              key="__create__"
              type="button"
              onClick={handleCreateWorkspace}
              disabled={creatingWorkspace}
              onMouseEnter={() => setHoveredId('__create__')}
              onMouseLeave={() => setHoveredId(null)}
              style={{
                width: '100%',
                height: cardHeight,
                borderRadius: '20px',
                border: '1px solid #e5e7ed',
                background: hoveredId === '__create__' ? '#fafbff' : '#fff',
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'center',
                justifyContent: 'center',
                cursor: creatingWorkspace ? 'progress' : 'pointer',
                transition: 'background 0.15s, border-color 0.15s',
                gap: '14px',
                appearance: 'none',
                padding: 0,
                opacity: creatingWorkspace ? 0.72 : 1,
              }}
            >
              <div style={{
                width: '56px',
                height: '56px',
                borderRadius: '50%',
                background: '#eef0fb',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                fontSize: '30px',
                color: '#5c5fbc',
                fontWeight: 300,
                lineHeight: 1,
              }}>
                +
              </div>
              <span style={{ fontSize: '14px', color: '#444', fontWeight: 500 }}>
                {creatingWorkspace ? t('home.creating') : t('home.createNew')}
              </span>
            </button>
          );

          const renderWorkspaceCard = (workspace: Workspace, globalIndex: number) => {
            const bg = CARD_COLORS[globalIndex % CARD_COLORS.length];
            const isHovered = hoveredId === workspace.id;
            return (
              <div
                key={workspace.id}
                onClick={() => router.push(`/workspace/${workspace.id}`)}
                onMouseEnter={() => setHoveredId(workspace.id)}
                onMouseLeave={() => setHoveredId(null)}
                style={{
                  height: cardHeight,
                  borderRadius: '20px',
                  background: bg,
                  filter: isHovered ? 'brightness(0.97)' : 'none',
                  cursor: 'pointer',
                  padding: cardPadding,
                  display: 'flex',
                  flexDirection: 'column',
                  position: 'relative',
                  transition: 'filter 0.15s',
                  boxSizing: 'border-box',
                }}
              >
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                  <WorkspaceIcon color="#5c5fbc" />
                  <div onClick={e => e.stopPropagation()}>
                    <WorkspaceMenu
                      onEditTitle={() => handleEditTitle(workspace)}
                      onDelete={() => handleDeleteWorkspace(workspace.id)}
                      onExport={() => handleExportWorkspace(workspace.id)}
                    />
                  </div>
                </div>
                <div style={{ marginTop: 'auto' }}>
                  <div
                    style={{
                      fontSize: titleSize,
                      fontWeight: 500,
                      color: '#1a1a2e',
                      marginBottom: '8px',
                      lineHeight: 1.25,
                      letterSpacing: '-0.2px',
                      display: '-webkit-box',
                      WebkitLineClamp: 2,
                      WebkitBoxOrient: 'vertical',
                      overflow: 'hidden',
                    }}
                  >
                    {workspace.name}
                  </div>
                  <div style={{ fontSize: '12.5px', color: '#6b7280' }}>
                    {formatDate(workspace.updatedAt)} · {t('home.sources', { count: workspace.sourceCount ?? 0 })}
                  </div>
                </div>
              </div>
            );
          };

          const gridStyle = {
            display: 'grid',
            gridTemplateColumns: isMobile ? 'repeat(1, 1fr)' : 'repeat(auto-fill, minmax(260px, 1fr))',
            gap: isMobile ? '14px' : '20px',
            marginTop: '14px',
          } as const;

          if (workspaces.length === 0) {
            // Empty state: render Create card alone, no group dividers
            return <div style={gridStyle}>{createCard}</div>;
          }

          // Global index map → keeps each workspace's CARD_COLORS slot stable
          // across toggles, and across "load more" pages.
          const indexById = new Map<string, number>();
          workspaces.forEach((ws, i) => indexById.set(ws.id, i));

          const groups = groupWorkspaces(workspaces, new Date());

          return (
            <div>
              {groups.map((group, gIdx) => (
                <section key={group.key} style={{ marginBottom: gIdx === groups.length - 1 ? 0 : '28px' }}>
                  {/* Divider row: thin line + left-aligned label chip */}
                  <div style={{
                    position: 'relative',
                    height: '1px',
                    background: '#e5e5ec',
                    marginTop: gIdx === 0 ? '8px' : 0,
                  }}>
                    <span style={{
                      position: 'absolute',
                      top: '-9px',
                      left: 0,
                      display: 'inline-block',
                      padding: '0 10px 0 0',
                      background: '#f8f9fa',
                      color: '#777',
                      fontSize: '12px',
                      fontWeight: 500,
                      letterSpacing: '0.2px',
                    }}>
                      {t(group.labelKey)}
                    </span>
                  </div>

                  <div style={gridStyle}>
                    {gIdx === 0 && createCard}
                    {group.items.map(ws => renderWorkspaceCard(ws, indexById.get(ws.id) ?? 0))}
                  </div>
                </section>
              ))}
            </div>
          );
        })()}

        {/* Load more */}
        {hasMore && (
          <div style={{ textAlign: 'center', marginTop: '24px' }}>
            <button
              onClick={loadMore}
              disabled={loadingMore}
              style={{
                padding: '8px 24px',
                borderRadius: '8px',
                border: '1px solid #d9d9d9',
                background: '#fff',
                cursor: loadingMore ? 'not-allowed' : 'pointer',
                fontSize: '14px',
                color: '#555',
              }}
            >
              {loadingMore ? t('home.loadingMore') : t('home.loadMore', { remaining: totalCount - workspaces.length })}
            </button>
          </div>
        )}
      </div>

      {/* Delete confirmation dialog */}
      {deletingWorkspaceId && (
        <>
          <div
            onClick={() => setDeletingWorkspaceId(null)}
            style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.25)', zIndex: 1000 }}
          />
          <div style={{
            position: 'fixed', top: '50%', left: '50%',
            transform: 'translate(-50%, -50%)',
            background: '#fff', borderRadius: '12px',
            boxShadow: '0 8px 32px rgba(0,0,0,0.16)',
            padding: '24px', width: '360px', maxWidth: '90vw',
            zIndex: 1001,
          }}>
            <div style={{ fontWeight: 600, fontSize: '16px', marginBottom: '8px' }}>{t('home.deleteTitle')}</div>
            <div style={{ fontSize: '14px', color: '#555', marginBottom: '20px' }}>{t('home.deleteConfirm')}</div>
            <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '8px' }}>
              <button
                onClick={() => setDeletingWorkspaceId(null)}
                style={{
                  padding: '6px 16px', borderRadius: '6px',
                  border: '1px solid #d9d9d9', background: '#fff',
                  cursor: 'pointer', fontSize: '14px',
                }}
              >
                {t('common.cancel')}
              </button>
              <button
                onClick={handleConfirmDelete}
                style={{
                  padding: '6px 16px', borderRadius: '6px',
                  border: 'none', background: '#e53e3e',
                  color: '#fff', cursor: 'pointer', fontSize: '14px',
                }}
              >
                {t('common.delete')}
              </button>
            </div>
          </div>
        </>
      )}

      {/* Edit title dialog — custom, no antd Modal to avoid React 18.3 ref warning */}
      {editingWorkspace && (
        <>
          <div
            onClick={() => setEditingWorkspace(null)}
            style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.25)', zIndex: 1000 }}
          />
          <div style={{
            position: 'fixed', top: '50%', left: '50%',
            transform: 'translate(-50%, -50%)',
            background: '#fff', borderRadius: '12px',
            boxShadow: '0 8px 32px rgba(0,0,0,0.16)',
            padding: '24px', width: '380px', maxWidth: '90vw',
            zIndex: 1001,
          }}>
            <div style={{ fontWeight: 600, fontSize: '16px', marginBottom: '16px' }}>{t('home.editTitle')}</div>
            <input
              value={editingName}
              onChange={e => setEditingName(e.target.value)}
              onKeyDown={e => { if (e.key === 'Enter') handleSaveTitle(); if (e.key === 'Escape') setEditingWorkspace(null); }}
              autoFocus
              style={{
                width: '100%', padding: '8px 12px',
                border: '1px solid #d9d9d9', borderRadius: '6px',
                fontSize: '14px', outline: 'none', boxSizing: 'border-box',
              }}
              onFocus={e => (e.currentTarget.style.borderColor = '#5c5fbc')}
              onBlur={e => (e.currentTarget.style.borderColor = '#d9d9d9')}
            />
            <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '8px', marginTop: '20px' }}>
              <button
                onClick={() => setEditingWorkspace(null)}
                style={{
                  padding: '6px 16px', borderRadius: '6px',
                  border: '1px solid #d9d9d9', background: '#fff',
                  cursor: 'pointer', fontSize: '14px',
                }}
              >
                {t('common.cancel')}
              </button>
              <button
                onClick={handleSaveTitle}
                disabled={!editingName.trim()}
                style={{
                  padding: '6px 16px', borderRadius: '6px',
                  border: 'none', background: editingName.trim() ? '#5c5fbc' : '#d9d9d9',
                  color: '#fff', cursor: editingName.trim() ? 'pointer' : 'not-allowed',
                  fontSize: '14px',
                }}
              >
                {t('common.save')}
              </button>
            </div>
          </div>
        </>
      )}

      <SettingsModal open={settingsOpen} onClose={() => setSettingsOpen(false)} initialSection={settingsSection} />
    </div>
  );
}
