import React from 'react';
import { DragDropContext, DropResult } from '@hello-pangea/dnd';
import { useBuilder } from './BuilderContext';
import LeftSidebar from './LeftSidebar';
import RightSidebar from './RightSidebar';
import Canvas from './Canvas';
import { ElementType } from './types';
import { Button } from '@/components/ui/button';
import { ArrowRightIcon, SaveIcon, MonitorIcon, SmartphoneIcon, EyeIcon } from 'lucide-react';
import Link from 'next/link';
import { savePageContent } from '@/app/actions/store-pages';
import { toast } from 'sonner';
import { SidebarTrigger } from '@/components/ui/sidebar';

export default function BuilderWorkspace({ pageTitle, pageId, onSaveOverride }: { pageTitle?: string; pageId?: string; onSaveOverride?: (data: any) => Promise<{success: boolean, error?: string}> }) {
  const { data, setData, leftSidebarOpen, setLeftSidebarOpen, rightSidebarOpen, setRightSidebarOpen } = useBuilder();
  const [deviceMode, setDeviceMode] = React.useState<'desktop'|'mobile'>('desktop');

  const onDragEnd = (result: DropResult) => {
    const { source, destination, draggableId } = result;
    if (!destination) return;

    if (source.droppableId === 'elements_panel' && destination.droppableId.startsWith('col_')) {
      const type = draggableId.replace('new_', '') as ElementType;
      const targetColId = destination.droppableId;
      
      setData(prev => {
        const newData = JSON.parse(JSON.stringify(prev));
        for (const section of newData.sections) {
          const colIndex = section.columns.findIndex((c: any) => c.id === targetColId);
          if (colIndex > -1) {
            const newElement = {
              id: `el_${Date.now()}`,
              type,
              props: {}
            };
            section.columns[colIndex].elements.splice(destination.index, 0, newElement);
            break;
          }
        }
        return newData;
      });
    } else if (source.droppableId.startsWith('col_') && destination.droppableId.startsWith('col_')) {
       // Reordering logic
       setData(prev => {
          const newData = JSON.parse(JSON.stringify(prev));
          let draggedElement: any = null;
          
          // Remove from source
          for (const section of newData.sections) {
             const col = section.columns.find((c: any) => c.id === source.droppableId);
             if (col) {
                draggedElement = col.elements.splice(source.index, 1)[0];
                break;
             }
          }
          
          if (!draggedElement) return prev;

          // Add to destination
          for (const section of newData.sections) {
             const col = section.columns.find((c: any) => c.id === destination.droppableId);
             if (col) {
                col.elements.splice(destination.index, 0, draggedElement);
                break;
             }
          }
          return newData;
       });
    }
  };

  const [isSaving, setIsSaving] = React.useState(false);

  const handleSave = async () => {
    setIsSaving(true);
    let res;
    if (onSaveOverride) {
      res = await onSaveOverride(data);
    } else {
      if (!pageId) {
        toast.error('شناسه برگه یافت نشد. این برگه موقتی است.');
        setIsSaving(false);
        return;
      }
      res = await savePageContent(pageId, JSON.stringify(data));
    }
    setIsSaving(false);
    if (res.success) {
      toast.success('محتوای طراحی با موفقیت ذخیره شد!');
    } else {
      toast.error('خطا در ذخیره: ' + (res.error || ''));
    }
  };

  return (
    <div className="flex flex-col h-full w-full relative">
      {/* Topbar */}
      <header className="h-16 border-b bg-white dark:bg-slate-900 flex items-center justify-between px-4 shrink-0 z-10 shadow-sm">
        <div className="flex items-center gap-2.5">
          <SidebarTrigger />
          <Link href="/storefront/pages">
            <Button variant="ghost" size="sm" className="gap-2 text-muted-foreground">
              بازگشت
            </Button>
          </Link>
          <div className="h-4 w-px bg-border mx-1" />
          <h1 className="font-bold text-sm ml-4">{pageTitle || "طراحی برگه"}</h1>
          
          <div className="flex items-center bg-muted/50 p-1 rounded-lg">
            <Button variant={leftSidebarOpen ? "secondary" : "ghost"} size="sm" className="h-7 text-xs px-3" onClick={() => setLeftSidebarOpen(!leftSidebarOpen)}>
               المان‌ها
            </Button>
            <Button variant={rightSidebarOpen ? "secondary" : "ghost"} size="sm" className="h-7 text-xs px-3" onClick={() => setRightSidebarOpen(!rightSidebarOpen)}>
               تنظیمات
            </Button>
          </div>
        </div>
        
        <div className="flex items-center gap-1 bg-muted p-1 rounded-lg">
          <Button variant={deviceMode === 'desktop' ? 'secondary' : 'ghost'} size="sm" className="h-7 px-2" onClick={() => setDeviceMode('desktop')}>
            <MonitorIcon className="w-4 h-4" />
          </Button>
          <Button variant={deviceMode === 'mobile' ? 'secondary' : 'ghost'} size="sm" className="h-7 px-2" onClick={() => setDeviceMode('mobile')}>
            <SmartphoneIcon className="w-4 h-4" />
          </Button>
        </div>

        <div className="flex items-center gap-2">
          <Button size="sm" variant="outline" className="gap-2 text-muted-foreground">
             <EyeIcon className="w-4 h-4" /> پیش‌نمایش
          </Button>
          <Button size="sm" className="gap-2 bg-indigo-600 hover:bg-indigo-700 text-white" onClick={handleSave} disabled={isSaving}>
            <SaveIcon className={`w-4 h-4 ${isSaving ? 'animate-pulse' : ''}`} />
            {isSaving ? 'در حال ذخیره...' : 'ذخیره و انتشار'}
          </Button>
        </div>
      </header>

      <DragDropContext onDragEnd={onDragEnd}>
      <div className={`flex flex-1 overflow-hidden relative`}>
        {leftSidebarOpen && <LeftSidebar />}
        <div className={`flex-1 overflow-y-auto relative py-8`}>
          <div className={`transition-all duration-300 origin-top shadow-2xl bg-white dark:bg-slate-900 border rounded-sm ${deviceMode === 'mobile' ? 'w-[375px] min-h-[812px] mx-auto overflow-hidden' : 'w-[calc(100%-2rem)] max-w-[1400px] min-h-[1000px] mx-auto'}`}>
             <Canvas />
          </div>
        </div>
        {rightSidebarOpen && <RightSidebar />}
      </div>
    </DragDropContext>
    </div>
  );
}
