'use client';

import Link from 'next/link';
import { useSession } from 'next-auth/react';
import { signOutToPath } from '@/lib/auth-client';
import dynamic from 'next/dynamic';
import { useRouter } from 'next/navigation';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { AnimatePresence, motion } from 'framer-motion';
import { BarChart3, CreditCard, LayoutDashboard, LifeBuoy, Link as LinkIcon, LogOut, Send, Settings, Shield, StickyNote } from 'lucide-react';
import ApiErrorAlert from '@/app/components/ApiErrorAlert';
import ProfileSettingsModal from '@/app/components/ProfileSettingsModal';
import ProfileCurrentPlanStrip from '@/app/components/profile/ProfileCurrentPlanStrip';
import ProfileTabSkeleton from '@/app/components/profile/ProfileTabSkeleton';
import ProfileSidebar from '@/app/components/profile/ProfileSidebar';
import ProfileTopbar from '@/app/components/profile/ProfileTopbar';
import { useProfileAccountIdentity } from '@/app/profile/hooks/useProfileAccountIdentity';
import { useProfileDashboardData } from '@/app/profile/hooks/useProfileDashboardData';
import { type ProfileDashboardTab } from '@/app/profile/hooks/useProfileDashboardTabs';
import { useProfileFilters } from '@/app/profile/hooks/useProfileFilters';
import { useProfileOverviewData } from '@/app/profile/hooks/useProfileOverviewData';
import { PROFILE_TAB_PATH, getProfileTabPath } from '@/app/profile/navigation';
import { getRuntimeClientConfig } from '@/lib/runtime-client-config';

type ProfileDashboardPageProps = {
  currentTab: ProfileDashboardTab;
  selectedLinkStatsId?: string | null;
};

function TabSectionLoading() {
  return (
    <div className="flex min-h-[260px] items-center justify-center rounded-2xl border border-white/10 bg-white/[0.02] backdrop-blur-md">
      <div className="text-center">
        <div className="mx-auto mb-2 h-7 w-7 animate-spin rounded-full border-2 border-violet-400 border-t-transparent" />
        <p className="text-xs uppercase tracking-[0.16em] text-gray-500">Loading</p>
      </div>
    </div>
  );
}

const ProfileOverviewTab = dynamic(() => import('@/app/components/profile/ProfileOverviewTab'), {
  loading: () => <ProfileTabSkeleton mode="overview" />,
});

const ProfileAnalyticsTab = dynamic(() => import('@/app/components/profile/ProfileAnalyticsTab'), {
  loading: () => <ProfileTabSkeleton mode="analytics" />,
});

const ProfileLinksTab = dynamic(() => import('@/app/components/profile/ProfileLinksTab'), {
  loading: () => <TabSectionLoading />,
});

const ProfileLinkStatsView = dynamic(() => import('@/app/components/profile/ProfileLinkStatsView'), {
  loading: () => <TabSectionLoading />,
});

const Pricing = dynamic(() => import('@/app/components/Pricing'), {
  loading: () => <TabSectionLoading />,
});

const ProfileNotebookTab = dynamic(() => import('@/app/components/profile/ProfileNotebookTab'), {
  loading: () => <TabSectionLoading />,
});

export function DashboardLoadingState() {
  return (
    <div className="flex min-h-screen items-center justify-center bg-[#050505]">
      <div className="text-center">
        <div className="mx-auto mb-3 h-8 w-8 animate-spin rounded-full border-2 border-violet-400 border-t-transparent" />
        <p className="text-sm text-gray-400">Загрузка dashboard...</p>
      </div>
    </div>
  );
}

function MobileMenu({
  open,
  currentTab,
  onTabChange,
  onClose,
  isAdmin,
  appName,
  supportEmail,
  supportTelegramUsername,
  onOpenSettings,
  onLogout,
}: {
  open: boolean;
  currentTab: ProfileDashboardTab;
  onTabChange: (tab: ProfileDashboardTab) => void;
  onClose: () => void;
  isAdmin: boolean;
  appName: string;
  supportEmail: string;
  supportTelegramUsername: string;
  onOpenSettings: () => void;
  onLogout: () => void;
}) {
  if (!open) return null;

  const items: Array<{ id: ProfileDashboardTab; label: string; Icon: typeof LayoutDashboard }> = [
    { id: 'overview', label: 'Обзор', Icon: LayoutDashboard },
    { id: 'links', label: 'Ссылки', Icon: LinkIcon },
    { id: 'analytics', label: 'Аналитика', Icon: BarChart3 },
    { id: 'pricing', label: 'Тарифы', Icon: CreditCard },
    { id: 'notebook', label: 'Записки', Icon: StickyNote },
  ];

  return (
    <div className="fixed inset-0 z-50 lg:hidden">
      <button type="button" className="absolute inset-0 bg-black/70" onClick={onClose} />
      <div className="absolute left-0 top-0 flex h-full w-72 flex-col border-r border-white/10 bg-[#0A0A0A] p-4 backdrop-blur-md">
        <Link
          href="/"
          onClick={onClose}
          className="mb-4 inline-flex items-center gap-2 rounded-lg px-1 py-1 transition-colors hover:text-violet-300"
        >
          <span className="inline-flex h-7 w-7 items-center justify-center rounded-lg bg-gradient-to-br from-fuchsia-500 to-violet-600 text-white shadow-[0_0_20px_rgba(139,92,246,0.24)]">
            <LinkIcon className="h-4 w-4" strokeWidth={2.5} />
          </span>
          <span className="text-sm font-semibold tracking-tight text-white">{appName}</span>
        </Link>

        <p className="mb-4 text-xs font-semibold uppercase tracking-[0.16em] text-gray-500">Навигация</p>
        <div className="space-y-1">
          {items.map(({ id, label, Icon }) => {
            const active = currentTab === id;
            return (
              <button
                key={id}
                type="button"
                onClick={() => {
                  onTabChange(id);
                  onClose();
                }}
                className={`inline-flex w-full items-center gap-2 rounded-lg border px-3 py-2 text-sm font-medium transition-all ${
                  active
                    ? 'border-white/10 bg-white/5 text-white'
                    : 'border-transparent bg-transparent text-gray-400 hover:bg-white/[0.03] hover:text-white'
                }`}
              >
                <Icon className={`h-4 w-4 ${active ? 'text-violet-300' : 'text-gray-500'}`} />
                {label}
              </button>
            );
          })}
        </div>

        <div className="mt-auto space-y-1 border-t border-white/10 pt-4">
          {isAdmin ? (
            <Link
              href="/admin"
              onClick={onClose}
              className="inline-flex w-full items-center gap-2 rounded-lg border border-white/10 bg-white/[0.03] px-3 py-2 text-sm text-gray-200 transition-all hover:bg-white/[0.08] hover:text-white"
            >
              <Shield className="h-4 w-4 text-violet-300" />
              Админ-панель
            </Link>
          ) : null}

          <button
            type="button"
            onClick={() => {
              onClose();
              onOpenSettings();
            }}
            className="inline-flex w-full items-center gap-2 rounded-lg border border-white/10 bg-white/[0.03] px-3 py-2 text-sm text-gray-200 transition-all hover:bg-white/[0.08] hover:text-white"
          >
            <Settings className="h-4 w-4 text-gray-400" />
            Настройки
          </button>

          {supportTelegramUsername ? (
            <a
              href={`https://t.me/${supportTelegramUsername}`}
              target="_blank"
              rel="noreferrer"
              onClick={onClose}
              className="inline-flex w-full items-center gap-2 rounded-lg border border-white/10 bg-white/[0.03] px-3 py-2 text-sm text-gray-200 transition-all hover:border-[#2AABEE]/25 hover:bg-[#2AABEE]/8 hover:text-white"
            >
              <Send className="h-4 w-4 text-[#2AABEE]" />
              Поддержка
            </a>
          ) : supportEmail ? (
            <a
              href={`mailto:${supportEmail}`}
              onClick={onClose}
              className="inline-flex w-full items-center gap-2 rounded-lg border border-white/10 bg-white/[0.03] px-3 py-2 text-sm text-gray-200 transition-all hover:border-violet-500/25 hover:bg-violet-500/8 hover:text-white"
            >
              <LifeBuoy className="h-4 w-4 text-violet-300" />
              Поддержка
            </a>
          ) : null}

          <button
            type="button"
            onClick={() => {
              onClose();
              onLogout();
            }}
            className="inline-flex w-full items-center gap-2 rounded-lg border border-red-500/20 bg-red-500/10 px-3 py-2 text-sm text-red-200 transition-all hover:bg-red-500/20"
          >
            <LogOut className="h-4 w-4" />
            Выйти
          </button>
        </div>
      </div>
    </div>
  );
}

export default function ProfileDashboardPage({ currentTab, selectedLinkStatsId = null }: ProfileDashboardPageProps) {
  const { data: session, status } = useSession();
  const router = useRouter();

  const sessionUser = session?.user;
  const effectiveUserId = sessionUser?.id;
  const profileCacheKey = effectiveUserId;
  const sessionReady = status === 'authenticated';
  const shouldLoadOverview = currentTab !== 'pricing' && currentTab !== 'notebook';

  const {
    searchParamsKey,
    billingStatus,
    folderId,
    isFavorite,
    tagIds,
    searchQuery,
    sortBy,
    linksPeriod,
  } = useProfileFilters();
  const { displayName, avatarInitials, isAdmin } = useProfileAccountIdentity(sessionUser);
  const {
    folders,
    tags,
    planState,
    isLoading: isDashboardDataLoading,
    error: dashboardDataError,
    refetch: refetchDashboardData,
  } = useProfileDashboardData(sessionReady, profileCacheKey);
  const {
    data: overviewData,
    isLoading: isOverviewLoading,
    error: overviewError,
    refetch: refetchOverviewData,
  } = useProfileOverviewData(sessionReady && shouldLoadOverview, profileCacheKey);

  const [showMobileMenu, setShowMobileMenu] = useState(false);
  const [topbarSearchValue, setTopbarSearchValue] = useState(searchQuery);
  const [liveSearchQuery, setLiveSearchQuery] = useState(searchQuery);
  const [isSettingsModalOpen, setIsSettingsModalOpen] = useState(false);
  const runtimeConfig = useMemo(() => getRuntimeClientConfig(), []);
  const appName = runtimeConfig.projectName || 'LinkSnap';
  const supportEmail = (runtimeConfig.supportEmail || '').trim();
  const supportTelegramUsername = (runtimeConfig.supportTelegramUsername || '').trim().replace(/^@+/, '');

  const currentPath = getProfileTabPath(currentTab);

  useEffect(() => {
    setTopbarSearchValue(searchQuery);
    setLiveSearchQuery(searchQuery);
  }, [searchQuery]);

  useEffect(() => {
    if (status === 'unauthenticated') {
      router.replace(`/login?returnTo=${encodeURIComponent(currentPath)}`, { scroll: false });
    }
  }, [currentPath, status, router]);

  useEffect(() => {
    if (status !== 'authenticated') return;

    Object.values(PROFILE_TAB_PATH).forEach((path) => {
      router.prefetch(path);
    });

    if (isAdmin) {
      router.prefetch('/admin');
    }
  }, [isAdmin, router, status]);

  useEffect(() => {
    if (status !== 'authenticated') return;

    const timer = window.setTimeout(() => {
      void import('@/app/components/profile/ProfileLinksTab');
      void import('@/app/components/Pricing');
      void import('@/app/components/profile/ProfileNotebookTab');
    }, 350);

    return () => window.clearTimeout(timer);
  }, [status]);

  const navigateToTab = useCallback(
    (tab: ProfileDashboardTab) => {
      const targetPath = getProfileTabPath(tab);
      if (targetPath === currentPath) return;
      router.push(targetPath, { scroll: false });
    },
    [currentPath, router]
  );

  const replaceTabQuery = useCallback(
    (tab: ProfileDashboardTab, params: URLSearchParams) => {
      const targetPath = getProfileTabPath(tab);
      const query = params.toString();
      router.replace(query ? `${targetPath}?${query}` : targetPath, { scroll: false });
    },
    [router]
  );

  const buildLinksParams = useCallback(() => {
    const params = new URLSearchParams();
    if (folderId) params.set('folderId', folderId);
    if (isFavorite) params.set('isFavorite', 'true');
    tagIds.forEach((id) => params.append('tagIds', id));
    if (sortBy !== 'newest') params.set('sort', sortBy);
    if (linksPeriod !== 'all') params.set('period', linksPeriod);
    return params;
  }, [folderId, isFavorite, linksPeriod, sortBy, tagIds]);

  useEffect(() => {
    const timer = window.setTimeout(() => {
      const next = topbarSearchValue.trim();
      setLiveSearchQuery((prev) => (prev === next ? prev : next));

      if (next && currentTab !== 'links') {
        const params = buildLinksParams();
        params.set('search', next);
        replaceTabQuery('links', params);
      }
    }, 240);

    return () => window.clearTimeout(timer);
  }, [buildLinksParams, currentTab, replaceTabQuery, topbarSearchValue]);

  useEffect(() => {
    const params = new URLSearchParams(searchParamsKey);
    if (params.get('settings') !== '1') return;

    setIsSettingsModalOpen(true);
    params.delete('settings');
    replaceTabQuery(currentTab, params);
  }, [currentTab, replaceTabQuery, searchParamsKey]);

  const summary = overviewData.summary;

  const handleRefreshDashboardState = useCallback(async () => {
    await Promise.all([refetchDashboardData(), refetchOverviewData()]);
  }, [refetchDashboardData, refetchOverviewData]);

  const handleClearBillingStatus = useCallback(() => {
    const params = new URLSearchParams(searchParamsKey);
    params.delete('billing');
    replaceTabQuery(currentTab, params);
  }, [currentTab, replaceTabQuery, searchParamsKey]);

  const handleFolderClick = useCallback(
    (selectedFolderId: string) => {
      const params = buildLinksParams();
      params.delete('folderId');
      if (selectedFolderId !== folderId) {
        params.set('folderId', selectedFolderId);
      }
      replaceTabQuery('links', params);
    },
    [buildLinksParams, folderId, replaceTabQuery]
  );

  const handleOpenCreate = useCallback(() => {
    const params = buildLinksParams();
    params.set('create', '1');
    replaceTabQuery('links', params);
  }, [buildLinksParams, replaceTabQuery]);

  const handleOpenSettings = useCallback(() => {
    setIsSettingsModalOpen(true);
  }, []);

  if (status === 'loading' || status === 'unauthenticated') {
    return <DashboardLoadingState />;
  }

  if (!session) {
    return null;
  }

  return (
    <div className="flex h-screen overflow-hidden bg-[#050505] text-white">
      <ProfileSidebar
        currentTab={currentTab}
        onTabChange={navigateToTab}
        folders={folders}
        activeFolderId={folderId}
        onFolderClick={handleFolderClick}
        onCreateClick={handleOpenCreate}
        displayName={displayName}
        avatarInitials={avatarInitials}
        isAdmin={isAdmin}
        onOpenSettings={handleOpenSettings}
        onLogout={() => signOutToPath('/')}
        onFoldersChanged={refetchDashboardData}
      />

      <main className="relative flex min-w-0 flex-1 flex-col">
        <div className="pointer-events-none absolute inset-0 bg-[radial-gradient(circle_at_top_right,_rgba(139,92,246,0.08),_transparent_58%)]" />

        <ProfileTopbar
          searchValue={topbarSearchValue}
          onSearchValueChange={setTopbarSearchValue}
          searchPlaceholder="Поиск по ссылкам, slug, папкам и тегам..."
          showSearch={currentTab === 'links'}
          onOpenMobileMenu={() => setShowMobileMenu(true)}
        />

        <div className="relative z-10 flex-1 overflow-y-auto p-4 md:p-6 lg:p-8">
          <ApiErrorAlert message={dashboardDataError || overviewError} className="mb-4" />

          <AnimatePresence mode="wait" initial={false}>
            {currentTab === 'overview' ? (
              <ProfileOverviewTab
                displayName={displayName}
                data={overviewData}
                planState={planState}
                availableAnalyticsPeriods={planState?.availableAnalyticsPeriods}
                isLoading={isOverviewLoading || isDashboardDataLoading}
                billingStatus={billingStatus}
                onClearBillingStatus={handleClearBillingStatus}
                onGoToLinks={() => navigateToTab('links')}
                onGoToAnalytics={() => navigateToTab('analytics')}
              />
            ) : null}

            {currentTab === 'analytics' ? (
              <ProfileAnalyticsTab
                data={overviewData}
                availableAnalyticsPeriods={planState?.availableAnalyticsPeriods}
                isLoading={isOverviewLoading || isDashboardDataLoading}
                onGoToLinks={() => navigateToTab('links')}
              />
            ) : null}

            {currentTab === 'links' ? (
              <motion.section
                key="links"
                initial={{ opacity: 0, y: 14 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -10 }}
                transition={{ duration: 0.24, ease: 'easeOut' }}
                className="mx-auto max-w-6xl"
              >
                {selectedLinkStatsId ? (
                  <ProfileLinkStatsView
                    linkId={selectedLinkStatsId}
                    embedded
                    availableAnalyticsPeriods={planState?.availableAnalyticsPeriods}
                    planFeatures={planState?.features}
                    onBack={() => router.push('/profile/links', { scroll: false })}
                  />
                ) : (
                  <ProfileLinksTab
                    cacheScope={profileCacheKey}
                    folderId={folderId}
                    isFavorite={isFavorite}
                    tagIds={tagIds}
                    searchQuery={liveSearchQuery}
                    sortBy={sortBy}
                    folders={folders}
                    tags={tags}
                    totalLinks={summary.totalLinks}
                    favoriteCount={summary.favoriteCount}
                    planState={planState}
                    onDataChanged={handleRefreshDashboardState}
                    onOpenSettingsModal={() => setIsSettingsModalOpen(true)}
                    onOpenStats={(linkId) => router.push(`/profile/links/${linkId}`, { scroll: false })}
                  />
                )}
              </motion.section>
            ) : null}

            {currentTab === 'pricing' ? (
              <motion.section
                key="pricing"
                initial={{ opacity: 0, y: 14 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -10 }}
                transition={{ duration: 0.24, ease: 'easeOut' }}
                className="mx-auto max-w-7xl"
              >
                <ProfileCurrentPlanStrip planState={planState} />
                <Pricing
                  currentPlanId={typeof planState?.plan === 'string' ? planState.plan : null}
                  currentBillingSource={planState?.billingSource}
                  currentPlanExpiresAt={planState?.expiresAt ?? null}
                />
              </motion.section>
            ) : null}

            {currentTab === 'notebook' ? (
              <motion.section
                key="notebook"
                initial={{ opacity: 0, y: 14 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -10 }}
                transition={{ duration: 0.24, ease: 'easeOut' }}
                className="mx-auto max-w-6xl"
              >
                <ProfileNotebookTab planState={planState} />
              </motion.section>
            ) : null}
          </AnimatePresence>
        </div>
      </main>

      <MobileMenu
        open={showMobileMenu}
        currentTab={currentTab}
        onTabChange={navigateToTab}
        onClose={() => setShowMobileMenu(false)}
        isAdmin={isAdmin}
        appName={appName}
        supportEmail={supportEmail}
        supportTelegramUsername={supportTelegramUsername}
        onOpenSettings={handleOpenSettings}
        onLogout={() => signOutToPath('/')}
      />

      <ProfileSettingsModal
        isOpen={isSettingsModalOpen}
        onClose={() => setIsSettingsModalOpen(false)}
        initialTelegramId={sessionUser?.telegramId ?? null}
        initialTelegramUsername={sessionUser?.telegramUsername ?? null}
      />
    </div>
  );
}
