import { useState, useEffect } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { FileText, File, Loader2, ExternalLink } from "lucide-react";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { supabase } from "@/lib/supabase";
import { useTranslation } from 'react-i18next';

interface CustomContentViewerProps {
  contentId: string;
  storeId: string;
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

interface ContentData {
  id: string;
  contentType: "text_entry" | "pdf_upload";
  title: string;
  contentText: string;
  originalFilename?: string;
  pageCount?: number;
  chunkCount: number;
  createdAt: string;
  pdfUrl?: string;
}

export function CustomContentViewer({
  contentId,
  storeId,
  open,
  onOpenChange,
}: CustomContentViewerProps) {
  const { t } = useTranslation();
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [content, setContent] = useState<ContentData | null>(null);
  const [activeTab, setActiveTab] = useState<string>("text");

  useEffect(() => {
    if (open && contentId && storeId) {
      fetchContent();
    }
  }, [open, contentId, storeId]);

  const fetchContent = async () => {
    setLoading(true);
    setError(null);

    try {
      const { data: { session } } = await supabase.auth.getSession();
      if (!session) throw new Error("Not authenticated");

      const response = await fetch(
        `${import.meta.env.VITE_API_URL}/custom-content-view?content_id=${contentId}&store_id=${storeId}`,
        {
          headers: {
            Authorization: `Bearer ${session.access_token}`,
          },
        }
      );

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || "Failed to fetch content");
      }

      const data = await response.json();
      setContent(data);

      // For PDFs, default to PDF view if URL is available
      if (data.contentType === "pdf_upload" && data.pdfUrl) {
        setActiveTab("pdf");
      }
    } catch (err: any) {
      console.error("Fetch content error:", err);
      setError(err.message || "Failed to load content");
    } finally {
      setLoading(false);
    }
  };

  const handleOpenPdfInNewTab = () => {
    if (content?.pdfUrl) {
      window.open(content.pdfUrl, '_blank');
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-4xl max-h-[90vh] bg-slate-800 border-slate-700">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2 text-white">
            {content?.contentType === "pdf_upload" ? (
              <File className="h-5 w-5 text-red-400" />
            ) : (
              <FileText className="h-5 w-5 text-blue-400" />
            )}
            {content?.title || t('customContent.viewer.loading')}
          </DialogTitle>
        </DialogHeader>

        <div className="space-y-4">
          {loading && (
            <div className="flex items-center justify-center py-12">
              <Loader2 className="h-8 w-8 animate-spin text-cyan-500" />
              <span className="ml-2 text-slate-400">{t('customContent.viewer.loading')}</span>
            </div>
          )}

          {error && (
            <Alert variant="destructive" className="bg-red-900/20 border-red-800">
              <AlertDescription className="text-red-200">{error}</AlertDescription>
            </Alert>
          )}

          {content && !loading && !error && (
            <>
              {/* Metadata */}
              <div className="flex items-center gap-4 text-sm text-slate-400 pb-2 border-b border-slate-700">
                {content.contentType === "pdf_upload" && content.originalFilename && (
                  <span>{content.originalFilename}</span>
                )}
                {content.pageCount && (
                  <span>{content.pageCount} {t('customContent.list.table.pages')}</span>
                )}
                <span>{content.chunkCount} {t('customContent.viewer.chunks')}</span>
                <span>{new Date(content.createdAt).toLocaleDateString()}</span>
              </div>

              {/* Content Viewer */}
              {content.contentType === "pdf_upload" && content.pdfUrl ? (
                <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
                  <TabsList className="bg-slate-700 border border-slate-600">
                    <TabsTrigger
                      value="pdf"
                      className="data-[state=active]:bg-slate-600 data-[state=active]:text-white text-slate-300"
                    >
                      <File className="h-4 w-4 mr-2" />
                      {t('customContent.viewer.pdfView')}
                    </TabsTrigger>
                    <TabsTrigger
                      value="text"
                      className="data-[state=active]:bg-slate-600 data-[state=active]:text-white text-slate-300"
                    >
                      <FileText className="h-4 w-4 mr-2" />
                      {t('customContent.viewer.textView')}
                    </TabsTrigger>
                  </TabsList>

                  <TabsContent value="pdf" className="mt-4">
                    <div className="space-y-2">
                      <div className="flex justify-end">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={handleOpenPdfInNewTab}
                          className="bg-slate-700 border-slate-600 text-white hover:bg-slate-600"
                        >
                          <ExternalLink className="h-4 w-4 mr-2" />
                          {t('customContent.viewer.openInNewTab')}
                        </Button>
                      </div>
                      <div className="bg-slate-900 rounded-lg border border-slate-700 overflow-hidden">
                        <iframe
                          src={content.pdfUrl}
                          className="w-full h-[600px]"
                          title={content.title}
                        />
                      </div>
                    </div>
                  </TabsContent>

                  <TabsContent value="text" className="mt-4">
                    <div className="bg-slate-900 rounded-lg p-4 border border-slate-700 max-h-[600px] overflow-y-auto">
                      <pre className="text-slate-200 whitespace-pre-wrap font-mono text-sm">
                        {content.contentText}
                      </pre>
                    </div>
                  </TabsContent>
                </Tabs>
              ) : (
                // Text entry - just show text
                <div className="bg-slate-900 rounded-lg p-4 border border-slate-700 max-h-[600px] overflow-y-auto">
                  <pre className="text-slate-200 whitespace-pre-wrap font-mono text-sm">
                    {content.contentText}
                  </pre>
                </div>
              )}
            </>
          )}
        </div>
      </DialogContent>
    </Dialog>
  );
}
