'use client';

import Image from "next/image";
import Link from 'next/link';
import TemplateSelector from '@/modals/template-selector';
import { useDesignStore } from '@/stores/design-store';
import { useTemplateStore } from '@/stores/template-store';

// import { PlusIcon, MagnifyingGlassIcon, Bars3Icon, Squares2X2Icon, FolderIcon, ClockIcon, EllipsisHorizontalIcon, ShareIcon, TrashIcon, ArrowUpOnSquareIcon, DocumentPlusIcon, UserGroupIcon } from "@heroicons/react/24/outline";
import {
  Plus,
  Search,
  AlignJustify, // For list view
  LayoutGrid,   // For grid view
  Folder as FolderIcon, // Alias to avoid conflict if 'Folder' component is used elsewhere
  Clock,
  MoreHorizontal,
  Share2,
  Trash2,
  UploadCloud,
  FilePlus2,
  FileText, // Generic icon for design cards
  FileEdit, // Added for designs with uncommitted changes
  // HelpCircle, // Removed as FAB was removed
  Github,
  Bell,         // For notifications
  Settings as SettingsIcon, // For settings
  BookOpenText, // For Docs
  ChevronDown,  // For dropdowns
  Shapes,
  GitPullRequest, // Added for Create PR button
  HelpCircle, // Added for Help and Feedback
  LogOut,      // Added for Log out
  Info,         // Added for the top banner
  FileJson,      // Added for JSON schema files
  ServerIcon,
  Network,      // For Domain type designs
  Workflow,      // For Flow type designs
  FolderInput
} from 'lucide-react';
import {
  Panel, 
  PanelGroup, 
  PanelResizeHandle 
} from "react-resizable-panels";
import { useState } from 'react';

export default function Page() {
  const { designs } = useDesignStore();
  const { setShowTemplateSelector } = useTemplateStore();
  // Sidebar main navigation item
  const workspaceSections = [
    { id: 1, name: "My Designs", count: designs.length, active: true, icon: FolderIcon },
  ];

  const githubRepos = [
    { id: 'repo1', name: "eventcatalog/eventcatalog", icon: Github },
    { id: 'repo2', name: "your-org/design-system", icon: Github },
    { id: 'repo3', name: "personal/new-project-x", icon: Github },
  ];

  // View and Search States
  type ViewMode = 'list' | 'grid';
  const [currentView, setCurrentView] = useState<ViewMode>('grid');
  const [searchTerm, setSearchTerm] = useState('');

  // Filtered Designs
  const filteredDesigns = designs.filter(design => {
    const term = searchTerm.toLowerCase();
    const typeMatch = design.type.toLowerCase().includes(term);
    const nameMatch = design.name.toLowerCase().includes(term);
    const descriptionMatch = design.description?.toLowerCase().includes(term) || false;
    const domainMatch = design.domainName?.toLowerCase().includes(term) || false;
    const eventNameMatch = design.eventName?.toLowerCase().includes(term) || false;
    const formatMatch = design.format?.toLowerCase().includes(term) || false;

    return typeMatch || nameMatch || descriptionMatch || domainMatch || eventNameMatch || formatMatch;
  });

  return (
    <div className="flex flex-col h-screen bg-slate-100 text-slate-800">
      {/* Preview Banner */}
      <div className="bg-purple-600 text-sm text-white px-4 py-2.5 flex items-center space-x-2.5 shadow-sm">
        <Info className="w-5 h-5 shrink-0" />
        <span>
          EventCatalog Studio is in public preview. By continuing to use EventCatalog Studio, you agree to the{' '}
          <a href="#" className="font-semibold hover:underline text-purple-200 hover:text-purple-50">
            preview terms
          </a>.
        </span>
      </div>

      {/* Global Header */}
      <header className="bg-white border-b border-slate-200 px-4 h-16 flex items-center justify-between shrink-0 z-10">
        <div className="flex items-center space-x-4">
          <div className="flex items-center space-x-2 text-sky-600">
            <Shapes className="w-7 h-7" /> {/* Or a more generic app icon like 'Layers' or 'Box' */}
            <span className="font-semibold text-lg text-slate-800">EventCatalog Studio</span>
          </div>
          <div className="h-6 border-l border-slate-300"></div>
          <button className="flex items-center space-x-1.5 px-3 py-1.5 rounded-md hover:bg-slate-100 transition-colors">
            <span className="text-sm font-medium text-slate-700">dave@eventcatalog</span>
            <ChevronDown className="w-4 h-4 text-slate-500" />
          </button>
          <button className="flex items-center space-x-1.5 px-3 py-1.5 rounded-md hover:bg-slate-100 transition-colors">
            <span className="text-sm font-medium text-slate-700">Design Project</span>
            <ChevronDown className="w-4 h-4 text-slate-500" />
          </button>
        </div>
        <div className="flex items-center space-x-4">
          <button className="p-2 text-slate-500 hover:text-slate-700 hover:bg-slate-100 rounded-full transition-colors">
            <Bell className="w-5 h-5" />
          </button>
          <a href="#" className="flex items-center space-x-1.5 text-sm text-slate-600 hover:text-sky-600 transition-colors">
            <BookOpenText className="w-5 h-5" />
            <span>Docs</span>
          </a>
          <a href="#" className="flex items-center space-x-1.5 text-sm text-slate-600 hover:text-sky-600 transition-colors">
            <SettingsIcon className="w-5 h-5" />
            <span>Settings</span>
          </a>
          <div className="w-8 h-8 bg-slate-300 rounded-full flex items-center justify-center text-slate-500 text-xs font-semibold">
            DS
          </div>
        </div>
      </header>

      <PanelGroup direction="horizontal" className="flex flex-1 overflow-hidden">
        <Panel defaultSize={20} minSize={15} maxSize={35} className="bg-white border-r border-slate-200 flex flex-col shrink-0">
          <div className="p-4 space-y-4 flex flex-col flex-grow overflow-y-auto">
            <div>
              <div className="flex items-center justify-between mb-2">
                <h2 className="text-xs font-semibold text-slate-500 uppercase tracking-wider">Workspace</h2>
              </div>
              {workspaceSections.map((folder) => {
                const IconComponent = folder.icon;
                return (
                  <a
                    key={folder.id}
                    href="#"
                    className={`flex items-center justify-between px-3 py-2 rounded-lg text-sm font-medium transition-colors duration-150
                      ${folder.active ? "bg-sky-50 text-sky-600" : "text-slate-600 hover:bg-slate-50 hover:text-slate-800"}`}
                  >
                    <div className="flex items-center space-x-2.5">
                      <IconComponent className={`w-5 h-5 ${folder.active ? 'text-sky-500' : 'text-slate-400'}`} />
                      <span>{folder.name}</span>
                    </div>
                    {folder.count > 0 && (
                      <span className={`text-xs font-normal px-1.5 py-0.5 rounded-full ${folder.active ? "bg-sky-100 text-sky-600" : "bg-slate-100 text-slate-500"}`}>
                        {folder.count}
                      </span>
                    )}
                    {folder.active && <button className="p-0.5 text-slate-400 hover:text-slate-600 rounded-md"><MoreHorizontal className="w-5 h-5" /></button>}
                  </a>
                );
              })}
            </div>
            <div className="border-b border-slate-200 -mx-4"></div>
            <div className="space-y-1 pr-1 -mr-1">
              <div className="flex items-center justify-between mb-2 mt-4">
                  <h2 className="text-xs font-semibold text-slate-500 uppercase tracking-wider">Repositories</h2>
                  <button className="p-1.5 text-slate-500 hover:bg-slate-100 hover:text-slate-700 rounded-md" title="Add Repository">
                      <Plus className="w-5 h-5" />
                  </button>
              </div>
              {githubRepos.map((repo) => (
                <a key={repo.id} href="#" className="flex items-center space-x-2.5 px-3 py-2 rounded-lg text-sm font-medium text-slate-600 hover:bg-slate-50 hover:text-slate-800 transition-colors duration-150 group">
                  <repo.icon className="w-5 h-5 text-slate-400 group-hover:text-slate-500" />
                  <span className="truncate" title={repo.name}>{repo.name}</span>
                </a>
              ))}
            </div>
            <a href="#" className="flex items-center space-x-2.5 px-3 py-2.5 rounded-lg text-sm font-medium text-slate-600 hover:bg-slate-50 hover:text-slate-800 transition-colors duration-150 mt-auto">
              <HelpCircle className="w-5 h-5 text-slate-400" />
              <span>Help and Feedback</span>
            </a>
          </div>
          <div className="p-4 border-t border-slate-200 shrink-0">
            <a href="#" className="flex items-center space-x-2.5 px-3 py-2.5 rounded-lg text-sm font-medium text-slate-600 hover:bg-slate-50 hover:text-slate-800 transition-colors duration-150">
              <LogOut className="w-5 h-5 text-slate-400" />
              <span>Log out</span>
            </a>
          </div>
        </Panel>
        <PanelResizeHandle className="w-1 bg-slate-200 hover:bg-sky-500 active:bg-sky-600 transition-colors duration-150 data-[resize-handle-state=drag]:bg-sky-600 data-[resize-handle-state=hover]:bg-sky-500" />
        
        <Panel className="flex-1 flex flex-col overflow-hidden">
          {/* Main Content Header: Search, View Options, New Button */}
          <header className="bg-white border-b border-slate-200 p-4 shrink-0 flex items-center justify-between">
            <div className="flex items-center space-x-3">
              <div className="relative">
                <Search className="w-5 h-5 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2" />
                <input
                  type="search"
                  placeholder="Search designs (e.g., by name, type, domain)..."
                  className="pl-10 pr-3 py-2 text-sm border border-slate-300 rounded-lg focus:ring-sky-500 focus:border-sky-500 w-72 transition-colors duration-150" // Increased width
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                />
              </div>
              <div className="flex items-center p-0.5 border border-slate-300 rounded-lg bg-slate-200">
                <button onClick={() => setCurrentView('list')} className={`p-1.5 rounded-md ${currentView === 'list' ? 'bg-white shadow-sm text-sky-600' : 'text-slate-500 hover:bg-slate-100 hover:text-slate-700'}`} title="List View" >
                  <AlignJustify className="w-5 h-5" />
                </button>
                <button onClick={() => setCurrentView('grid')} className={`p-1.5 rounded-md ${currentView === 'grid' ? 'bg-white shadow-sm text-sky-600' : 'text-slate-500 hover:bg-slate-100 hover:text-slate-700'}`} title="Grid View" >
                  <LayoutGrid className="w-5 h-5" />
                </button>
              </div>
            </div>
            <button onClick={() => setShowTemplateSelector(true)} className="bg-slate-900 hover:bg-slate-700 text-white font-medium py-1.5 px-3 text-sm rounded-lg shadow-sm flex items-center space-x-1.5 transition-colors duration-150">
              <FilePlus2 className="w-4 h-4"/>
              <span>New Design</span>
            </button>
          </header>

          {/* Content Listing Area */}
          <div className="flex-1 overflow-y-auto p-6 bg-slate-50">
            {filteredDesigns.length > 0 ? (
              <div className={`grid ${currentView === 'grid' ? 'gap-5 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4' : 'gap-3 grid-cols-1'}`}>
                {filteredDesigns.map((design) => {
                  const DesignIcon = FolderInput
                  const iconColorClass = design.hasUncommittedChanges ? 'bg-amber-500' :
                                         design.type === "Service" ? 'bg-pink-500' :
                                         design.type === "Flow" ? 'bg-teal-500' :
                                         design.type === "Domain" ? 'bg-rose-500' : 'bg-slate-500';

                  if (currentView === 'list') {
                    return (
                      <Link key={design.id} href={`/designs/${design.id}`} className="block bg-white rounded-lg shadow hover:shadow-md transition-shadow duration-200 border border-slate-200">
                        <div className="flex items-center p-3 space-x-4">
                          <div className={`w-10 h-10 rounded-lg flex items-center justify-center text-white ${iconColorClass} shrink-0`}>
                              <DesignIcon className="w-5 h-5 text-white" />
                          </div>
                          <div className="flex-grow overflow-hidden">
                              <div className="flex items-baseline space-x-2">
                                  <h3 className="text-sm font-semibold text-slate-800 truncate" title={design.name}>{design.name}</h3>
                                  <span className="text-xs text-slate-400 shrink-0">({design.type})</span>
                              </div>
                              {design.type === "Service" && <p className="text-xs text-slate-500 truncate" title={design.description}>{design.description} (Domain: {design.domainName})</p>}
                              {design.type === "Flow" && <p className="text-xs text-slate-500 truncate" title={design.description}>{design.description}</p>}
                              {design.type === "Domain" && <p className="text-xs text-slate-500 truncate" title={design.description}>{design.description}</p>}
                          </div>
                          <div className="flex items-center space-x-1 text-xs text-slate-500 shrink-0 whitespace-nowrap pr-2">
                              <Clock className="w-3.5 h-3.5" />
                              <span>{design.lastModified}</span>
                          </div>
                          {design.hasUncommittedChanges && (
                              <div className="ml-auto shrink-0">
                                <button className="p-1.5 bg-green-100 hover:bg-green-200 text-green-700 rounded-md text-xs transition-colors duration-150" title="Create Pull Request" onClick={(e) => e.stopPropagation()}>
                                  <GitPullRequest className="w-4 h-4" />
                                </button>
                              </div>
                          )}
                          <button className="p-1 text-slate-400 hover:text-slate-600 rounded-md shrink-0" onClick={(e) => e.stopPropagation()}>
                              <MoreHorizontal className="w-5 h-5" />
                          </button>
                        </div>
                      </Link>
                    );
                  } else { // Grid View
                    return (
                      <Link key={design.id} href={`/designs/${design.id}`} className="block bg-white rounded-xl shadow-md hover:shadow-lg transition-shadow duration-300 overflow-hidden border border-slate-200 h-full">
                        <div className="flex flex-col h-full">
                          <div className="p-5 flex-grow">
                            <div className="flex items-start justify-between mb-3">
                                <div className={`w-10 h-10 rounded-lg flex items-center justify-center text-white ${iconColorClass}`}>
                                    <DesignIcon className="w-6 h-6 text-white" />
                                </div>
                                <button className="p-1 text-slate-400 hover:text-slate-600 rounded-md" onClick={(e) => e.stopPropagation()}>
                                    <MoreHorizontal className="w-5 h-5" />
                                </button>
                            </div>
                            <h3 className="text-md font-semibold text-slate-800 mb-1 truncate" title={design.name}>{design.name}</h3>
                            <p className="text-xs text-slate-400 mb-1">{design.type}</p>
                            
                            {design.type === "Service" && <p className="text-xs text-slate-500 mb-1" title={design.domainName}>Domain: {design.domainName}</p>}
                            {design.type === "Flow" && <p className="text-xs text-slate-500 mb-1 truncate" title={design.description}>{/* Description might be too long for grid, consider summary or removing */}</p>}
                            {design.type === "Domain" && <p className="text-xs text-slate-500 mb-1 truncate" title={design.description}>{/* Description might be too long for grid, consider summary or removing */}</p>}
                            
                            <p className="text-xs text-slate-500 mb-3 h-8 overflow-hidden" title={design.description}>{design.description}</p>
                          </div>
                          <div className="border-t border-slate-200 bg-slate-50 px-5 py-3 mt-auto">
                            <div className="flex items-center justify-between text-xs text-slate-500">
                                <div className="flex items-center space-x-1.5"> <Clock className="w-3.5 h-3.5" /> <span>Edited {design.lastModified}</span> </div>
                            </div>
                            {design.hasUncommittedChanges && ( <div className="mt-2"> <button className="w-full flex items-center justify-center space-x-1.5 bg-green-500 hover:bg-green-600 text-white font-medium py-2 px-3 rounded-md text-xs transition-colors duration-150" onClick={(e) => e.stopPropagation()}> <GitPullRequest className="w-3.5 h-3.5" /> <span>Create Pull Request</span> </button> </div> )}
                          </div>
                        </div>
                      </Link>
                    );
                  }
                })}
              </div>
            ) : (
              <div className="text-center py-12">
                <FolderIcon className="w-16 h-16 text-slate-300 mx-auto mb-4" />
                <h3 className="text-xl font-medium text-slate-600 mb-1">No designs yet</h3>
                <p className="text-slate-500 mb-4 text-sm">Get started by creating a new design, or try a different search term.</p>
                <button onClick={() => setShowTemplateSelector(true)} className="bg-slate-900 hover:bg-slate-700 text-white font-medium py-2 px-4 text-sm rounded-lg shadow-sm flex items-center space-x-2 mx-auto transition-colors duration-150">
                  <FilePlus2 className="w-5 h-5"/>
                  <span>Create New Design</span>
                </button>
              </div>
            )}
          </div>
        </Panel>
      </PanelGroup>

      <TemplateSelector />

      {/* Floating Action Button (Optional) - REMOVING THIS
      <button className="fixed bottom-6 right-6 bg-purple-600 hover:bg-purple-700 text-white p-4 rounded-full shadow-xl transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:ring-offset-2">
        <HelpCircle className="w-6 h-6" />
      </button>
      */}
    </div>
  );
}
