import { useRoute, useLocation } from "wouter";
import { FileText, Presentation, Info, Search, Settings, User, LogOut } from "lucide-react";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { useQuery } from "@tanstack/react-query";
import { useAuth } from "@/hooks/useAuth";
import { useState } from "react";
import type { MediaOutlet } from "@shared/schema";
import Footer from "@/components/Footer";
import SearchModal from "@/components/SearchModal";

const reportContent: Record<string, { htmlPath: string; pptPath: string }> = {
  'chayan-asli': {
    htmlPath: '/attached_assets/chayan asli report_1759208054055.html',
    pptPath: '/attached_assets/chayan asli slides_1759213492580.pptx'
  },
  'krysh-parker': {
    htmlPath: '/attached_assets/krysh parker report_1759209671294.html',
    pptPath: '/attached_assets/krysh parker slides_1759209102236.pptx'
  }
};

export default function Report() {
  const [, params] = useRoute("/media/:slug/report");
  const [, setLocation] = useLocation();
  const [enlargedImage, setEnlargedImage] = useState<string | null>(null);
  const [isSearchModalOpen, setIsSearchModalOpen] = useState(false);
  const { user, isAuthenticated } = useAuth();
  
  const slug = params?.slug || '';
  const content = reportContent[slug] || reportContent['chayan-asli'];

  const { data: outlet, isLoading: outletLoading } = useQuery<MediaOutlet>({
    queryKey: ["/api/media-outlets", slug],
    enabled: !!slug
  });

  const handleLogout = async () => {
    try {
      const response = await fetch("/api/logout", {
        method: "POST",
        credentials: "include",
      });
      if (response.ok) {
        window.location.href = "/";
      }
    } catch (error) {
      console.error("Logout failed:", error);
    }
  };

  const handleAdminPage = () => {
    if (user?.role === "admin" || user?.role === "superadmin") {
      setLocation("/admin");
    }
  };
  
  // Get full URL for PPT file
  const getFullPptUrl = () => {
    const baseUrl = window.location.origin;
    return `${baseUrl}${content.pptPath}`;
  };

  // Remove margins and padding from iframe content
  const handleReportLoad = (e: React.SyntheticEvent<HTMLIFrameElement>) => {
    try {
      const iframe = e.currentTarget;
      const iframeDoc = iframe.contentDocument || iframe.contentWindow?.document;
      if (iframeDoc) {
        const style = iframeDoc.createElement('style');
        style.textContent = `
          html, body {
            margin: 0 !important;
            padding: 0 !important;
          }
          body > * {
            margin: 0 !important;
          }
          h1, h2, h3, h4, h5, h6, p, ul, ol, figure, blockquote {
            margin-top: 0 !important;
          }
          .report, .container, .page, .content {
            margin: 0 !important;
            padding: 8px !important;
          }
          @page {
            margin: 0 !important;
          }
        `;
        iframeDoc.head.appendChild(style);
      }
    } catch (e) {
      console.error('Could not inject styles into iframe:', e);
    }
  };

  return (
    <div className="flex flex-col min-h-screen bg-gray-50">
      {/* Header */}
      <header className="bg-white border-b border-gray-200 sticky top-0 z-50">
        <div className="max-w-7xl mx-auto px-6 py-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-3">
              {outletLoading ? (
                <>
                  <div className="w-10 h-10 bg-gray-200 rounded-full animate-pulse"></div>
                  <div className="flex flex-col">
                    <div className="h-1.5 w-16 bg-gray-200 rounded animate-pulse mb-0.5"></div>
                    <div className="h-5 w-24 bg-gray-200 rounded animate-pulse"></div>
                  </div>
                </>
              ) : outlet ? (
                <>
                  {outlet.imageUrl ? (
                    <img 
                      src={outlet.imageUrl} 
                      alt={outlet.name}
                      className="w-10 h-10 rounded-full object-cover cursor-pointer hover:ring-2 hover:ring-blue-400 transition-all"
                      onClick={() => setEnlargedImage(outlet.imageUrl!)}
                      data-testid="image-outlet-header-profile"
                    />
                  ) : (
                    <div className="w-10 h-10 bg-gray-100 rounded-full flex items-center justify-center">
                      <span className="text-gray-600 font-bold text-sm">
                        {outlet.name.charAt(0)}
                      </span>
                    </div>
                  )}
                  <div className="flex flex-col cursor-pointer hover:opacity-80 transition-opacity" onClick={() => setLocation("/")}>
                    <img 
                      src="/attached_assets/logo_black_1759162717640.png" 
                      alt="SAPIENS" 
                      className="h-1.5 w-auto max-w-[60px] mb-0.5"
                      data-testid="logo-sapiens"
                    />
                    <div className="flex items-center space-x-1.5">
                      <span className="text-lg font-bold text-gray-900" data-testid="text-outlet-name-header">
                        {outlet.name}
                      </span>
                      <TooltipProvider>
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <button
                              type="button"
                              onClick={(e) => e.stopPropagation()}
                              className="inline-flex items-center"
                              aria-label="View outlet information"
                            >
                              <Info 
                                className="h-4 w-4 text-gray-500 cursor-pointer hover:text-gray-700" 
                                data-testid="icon-info-header"
                              />
                            </button>
                          </TooltipTrigger>
                          <TooltipContent>
                            <p className="max-w-xs">{outlet.description || "Media Outlet"}</p>
                          </TooltipContent>
                        </Tooltip>
                      </TooltipProvider>
                    </div>
                  </div>
                </>
              ) : (
                <img 
                  src="/attached_assets/logo_black_1759162717640.png" 
                  alt="SAPIENS" 
                  className="h-6 w-auto cursor-pointer"
                  onClick={() => setLocation("/")}
                  data-testid="logo-sapiens"
                />
              )}
            </div>
            
            <div className="flex items-center space-x-4">
              <div 
                className="relative cursor-pointer"
                onClick={() => setIsSearchModalOpen(true)}
                data-testid="search-container"
              >
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400 pointer-events-none" />
                <Input 
                  type="text" 
                  placeholder="Search the website" 
                  className="w-80 pl-10 bg-gray-50 border-gray-200 cursor-pointer"
                  data-testid="input-search"
                  readOnly
                />
              </div>
              
              {isAuthenticated && user ? (
                <>
                  <Button 
                    variant="ghost" 
                    size="sm"
                    onClick={() => setLocation("/auctions")}
                    data-testid="button-auctions"
                  >
                    Auctions
                  </Button>
                  
                  <Button 
                    variant="ghost" 
                    size="sm"
                    onClick={handleAdminPage}
                    data-testid="button-admin-dashboard"
                  >
                    Admin Dashboard
                  </Button>
                  
                  <div className="flex items-center space-x-2 px-3 py-1 bg-gray-100 rounded-md">
                    <User className="h-4 w-4 text-gray-600" />
                    <span className="text-sm font-medium text-gray-700" data-testid="user-name">
                      {user.firstName} {user.lastName}
                    </span>
                  </div>
                  
                  <Button 
                    variant="ghost" 
                    size="sm"
                    onClick={handleLogout}
                    data-testid="button-logout"
                  >
                    <LogOut className="h-4 w-4" />
                  </Button>
                </>
              ) : (
                <Button 
                  variant="ghost" 
                  size="sm"
                  onClick={() => setLocation("/login")}
                  data-testid="button-login"
                >
                  Login
                </Button>
              )}
              
              <Button 
                variant="ghost" 
                size="sm"
                data-testid="button-settings"
              >
                <Settings className="h-4 w-4" />
              </Button>
            </div>
          </div>
        </div>
      </header>

      {/* Main Content */}
      <main className="flex-1 max-w-7xl mx-auto px-2 py-2 pb-32 w-full">
        <Tabs defaultValue="report" className="w-full">
          <TabsList className="grid w-full max-w-md mx-auto grid-cols-2 mb-4">
            <TabsTrigger value="report" data-testid="tab-report">
              <FileText className="h-4 w-4 mr-2" />
              Report
            </TabsTrigger>
            <TabsTrigger value="slides" data-testid="tab-slides">
              <Presentation className="h-4 w-4 mr-2" />
              Slides
            </TabsTrigger>
          </TabsList>

          <TabsContent value="report">
            <Card className="bg-white">
              <CardContent className="p-0">
                <iframe
                  src={content.htmlPath}
                  className="w-full border-none"
                  style={{ display: 'block', minHeight: '100vh', height: 'auto' }}
                  title="Comprehensive Report"
                  data-testid="iframe-report"
                  onLoad={handleReportLoad}
                />
              </CardContent>
            </Card>
          </TabsContent>

          <TabsContent value="slides" className="w-full">
            <div className="w-full bg-white rounded-lg overflow-hidden shadow-lg">
              <div className="relative w-full" style={{ paddingTop: '56.25%' }}>
                <iframe
                  src={`https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(getFullPptUrl())}`}
                  className="absolute top-0 left-0 w-full h-full border-none"
                  title="Presentation Slides"
                  data-testid="iframe-slides"
                  allowFullScreen
                  style={{ 
                    backgroundColor: 'white',
                    display: 'block'
                  }}
                />
              </div>
            </div>
          </TabsContent>
        </Tabs>
      </main>

      <Footer />
      
      {/* Search Modal */}
      <SearchModal
        isOpen={isSearchModalOpen}
        onClose={() => setIsSearchModalOpen(false)}
      />
    </div>
  );
}
