'use client';
import { Button } from '@/components/ui/button';
import { useToast } from '@/src/hooks/useToast';
import { cn } from '@/lib/utils';
import { SettingsButtons, SettingsPanel } from '@/src/components/builder/SettingsSidebar';
import { useAutosave } from '@/src/hooks/useAutosave';
import { usePortfolioRevisions, PortfolioRevisionService } from '@/src/services/PortfolioRevisionService';
import { PortfolioRevision, TopPanelProps } from '@/src/types/portfolio';
import { formatDistanceToNow } from 'date-fns';
import { Check, Eye, Save } from 'lucide-react';
import { useRouter } from 'next/navigation';
import { useState } from 'react';
import { HistoryPopover } from './common/HistoryPopover';
import { useApiWithToast } from '@/src/hooks/useApiWithToast';
import { usePortfolioConfig } from './context/PortfolioConfigContext';
import { AlertModal } from '@/components/common/AlertModal';

export function TopPanel({ name, className, portfolioId }: TopPanelProps) {
  const { revisions, isLoading: revisionsLoading } = usePortfolioRevisions(portfolioId);
  const { config, updateConfig, isDirty, saveConfig } = usePortfolioConfig();
  const router = useRouter();
  const { handle } = useApiWithToast();
  const { toast } = useToast();
  const [activePanel, setActivePanel] = useState<string | null>(null);
  const [isPanelOpen, setIsPanelOpen] = useState(false);
  const { getHistory, restoreVersion } = useAutosave(config, portfolioId);
  const [showConfirmDialog, setShowConfirmDialog] = useState(false);

  const recentChangesItems = getHistory().map((entry) => ({
    id: entry.timestamp.toString(),
    timestamp: entry.timestamp,
    title: formatDistanceToNow(new Date(entry.timestamp), {
      addSuffix: true,
    }),
    config: entry.config,
  }));

  const revisionItems =
    revisions?.map((revision) => ({
      id: revision.id,
      timestamp: new Date(revision.createdAt).getTime(),
      title: formatDistanceToNow(new Date(revision.createdAt), {
        addSuffix: true,
      }),
      subtitle: new Date(revision.createdAt).toLocaleString(),
    })) || [];

  const handleRestoreRecentChange = async (id: string) => {
    const timestamp = parseInt(id);
    const restoredConfig = restoreVersion(timestamp);

    if (restoredConfig) {
      updateConfig(restoredConfig);
      toast({
        title: 'Change restored',
        description: 'Recent change has been restored',
        variant: 'default',
      });
      return true;
    }
    return false;
  };

  const handlePreviewClick = () => {
    window.open(`/portfolios/${portfolioId}/preview`, '_blank');
  };

  const handleSave = async () => {
    if (!config) {
      toast({
        title: 'No changes to save',
        description: 'Add some elements to your portfolio before saving.',
        variant: 'default',
      });
      return;
    }
    saveConfig();
  };

  const handleRevisionSelect = async (revisionId: string): Promise<boolean> => {
    const revisionData = await handle<PortfolioRevision>(
      PortfolioRevisionService.getPortfolioRevision(portfolioId, revisionId)
    );
    if (revisionData) {
      updateConfig(revisionData.config);
      return true;
    }
    return false;
  };

  const handlePanelSelect = (panelId: string) => {
    if (activePanel === panelId) {
      setIsPanelOpen(!isPanelOpen);
    } else {
      setActivePanel(panelId);
      setIsPanelOpen(true);
    }
  };

  const handleToggleOpen = () => {
    setIsPanelOpen(!isPanelOpen);
  };

  const handleDoneEditing = () => {
    if (isDirty) {
      setShowConfirmDialog(true);
    } else {
      router.push('/dashboard');
    }
  };

  const handleConfirmLeave = () => {
    setShowConfirmDialog(false);
    router.push('/dashboard');
  };

  return (
    <>
      <div
        className={cn(
          'fixed top-0 left-0 right-0 h-14 bg-neutral-800 backdrop-blur-sm border-b z-[450]',
          'flex items-center justify-between px-4 text-white',
          className
        )}
      >
        <div className='flex items-center gap-1'>
          <Button variant='ghost' size='sm' onClick={handlePreviewClick} className='flex items-center gap-2'>
            <Eye className='h-4 w-4' />
            Preview
          </Button>
          <div className='h-4 w-px bg-neutral-600 mx-1' />
          <SettingsButtons
            onPanelSelect={handlePanelSelect}
            activePanel={activePanel}
            onToggleOpen={handleToggleOpen}
          />
        </div>
        <h2 className='text-lg font-semibold'>{name}</h2>
        <div className='flex items-center gap-1'>
          <HistoryPopover
            items={recentChangesItems}
            onRestore={handleRestoreRecentChange}
            isLoading={false}
            title='Recent Changes'
            description='Last few autosaved changes'
            icon='clock'
            buttonText='Recent Changes'
          />
          <HistoryPopover
            items={revisionItems}
            onRestore={handleRevisionSelect}
            isLoading={revisionsLoading}
            title='Revision History'
            description='Saved portfolio versions'
            icon='history'
            buttonText='History'
          />
          <Button variant='ghost' size='sm' onClick={handleSave} className='flex items-center gap-1'>
            <Save className='h-4 w-4' />
            Save
          </Button>
          <div className='h-4 w-px bg-neutral-600 mx-1' />
          <Button variant='ghost' size='sm' onClick={handleDoneEditing} className='flex items-center gap-1'>
            <Check className='h-4 w-4' />
            Done Editing
          </Button>
        </div>
      </div>

      <SettingsPanel
        activePanel={activePanel}
        onClose={() => setActivePanel(null)}
        isOpen={isPanelOpen}
        onToggleOpen={handleToggleOpen}
      />

      <AlertModal
        isOpen={showConfirmDialog}
        onClose={() => setShowConfirmDialog(false)}
        title='Unsaved Changes'
        description='You have unsaved changes. Are you sure you want to leave? Your changes will be lost.'
        onConfirm={handleConfirmLeave}
      />
    </>
  );
}
