import { useEffect, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Button } from "@/components/ui/button";
import { Trash2, FileText, File, Eye, RefreshCw, AlertTriangle } from "lucide-react";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { CustomContentStatusBadge } from "./CustomContentStatusBadge";
import { CustomContentViewer } from "./CustomContentViewer";
import { useToast } from "@/hooks/use-toast";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { supabase } from "@/lib/supabase";
import { useShop } from "@/components/context/ShopContext";
import { useTranslation } from 'react-i18next';

interface CustomContentListProps {
  contentType?: "text_entry" | "pdf_upload";
  refreshKey: number;
  onDelete: () => void;
}

interface ContentItem {
  id: string;
  title: string;
  contentType: string;
  originalFilename?: string;
  fileSize?: number;
  pageCount?: number;
  chunkCount: number;
  syncStatus: string;
  syncError?: string;
  createdAt: string;
}

export function CustomContentList({
  contentType,
  refreshKey,
  onDelete
}: CustomContentListProps) {
  const { t } = useTranslation();
  const [deleteId, setDeleteId] = useState<string | null>(null);
  const [viewContentId, setViewContentId] = useState<string | null>(null);
  const [retryingId, setRetryingId] = useState<string | null>(null);
  const { toast } = useToast();
  const { selectedShop } = useShop();

  // Fetch content list
  const { data, isLoading, refetch } = useQuery({
    queryKey: ["custom-content", selectedShop?.id, contentType, refreshKey],
    queryFn: async () => {
      const { data: { session } } = await supabase.auth.getSession();
      if (!session) throw new Error("Not authenticated");

      if (!selectedShop) throw new Error("No shop selected");

      const params = new URLSearchParams({
        store_id: selectedShop.id,
        ...(contentType && { content_type: contentType }),
      });

      const response = await fetch(
        `${import.meta.env.VITE_API_URL}/custom-content-list?${params}`,
        {
          headers: {
            Authorization: `Bearer ${session.access_token}`,
          },
        }
      );

      if (!response.ok) {
        throw new Error("Failed to fetch content");
      }

      const result = await response.json();
      return result.content as ContentItem[];
    },
    enabled: !!selectedShop,
  });

  // Refetch on refreshKey change
  useEffect(() => {
    if (refreshKey > 0) {
      refetch();
    }
  }, [refreshKey, refetch]);

  const handleRetry = async (id: string) => {
    if (!selectedShop) return;

    setRetryingId(id);
    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-retry`,
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${session.access_token}`,
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            content_id: id,
            store_id: selectedShop.id,
          }),
        }
      );

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

      toast({
        title: t('customContent.list.retry.successTitle'),
        description: t('customContent.list.retry.successDescription'),
      });

      // Refetch list to update status
      refetch();
    } catch (err: any) {
      toast({
        title: t('customContent.list.retry.errorTitle'),
        description: err.message,
        variant: "destructive",
      });
    } finally {
      setRetryingId(null);
    }
  };

  const handleDelete = async (id: string) => {
    if (!selectedShop) return;

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

      console.log('[Delete] Attempting to delete content:', id);
      console.log('[Delete] API URL:', import.meta.env.VITE_API_URL);

      const response = await fetch(
        `${import.meta.env.VITE_API_URL}/custom-content-delete`,
        {
          method: "DELETE",
          headers: {
            Authorization: `Bearer ${session.access_token}`,
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            content_id: id,
            store_id: selectedShop.id,
          }),
        }
      );

      console.log('[Delete] Response status:', response.status);

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({ error: 'Unknown error' }));
        throw new Error(errorData.error || `HTTP ${response.status}: Failed to delete content`);
      }

      toast({
        title: t('customContent.list.delete.successTitle'),
        description: t('customContent.list.delete.successDescription'),
      });

      onDelete();
    } catch (err: any) {
      console.error('[Delete] Error:', err);

      // Provide more specific error messages
      let errorMessage = err.message;
      if (err.message === 'Failed to fetch') {
        errorMessage = 'Network error. Please check your connection and try again.';
      }

      toast({
        title: t('customContent.list.delete.errorTitle'),
        description: errorMessage,
        variant: "destructive",
      });
    } finally {
      setDeleteId(null);
    }
  };

  if (isLoading) {
    return <div className="text-center py-8 text-slate-400">{t('customContent.list.loading')}</div>;
  }

  if (!data || data.length === 0) {
    return (
      <div className="text-center py-8 text-slate-400">
        {t('customContent.list.noContent')}
      </div>
    );
  }

  // Check for failed items
  const failedItems = data.filter(item => item.syncStatus === 'failed');
  const hasFailed = failedItems.length > 0;

  return (
    <>
      {/* Warning for failed processing */}
      {hasFailed && (
        <Alert variant="destructive" className="mb-4 bg-red-900/20 border-red-800">
          <AlertTriangle className="h-4 w-4" />
          <AlertTitle className="text-red-400">
            {t('customContent.list.failureWarning.title')}
          </AlertTitle>
          <AlertDescription className="text-red-300">
            {t('customContent.list.failureWarning.description')}
          </AlertDescription>
        </Alert>
      )}

      <div className="bg-slate-800 rounded-lg overflow-hidden border border-slate-700">
        <Table>
          <TableHeader>
            <TableRow className="border-slate-700 hover:bg-slate-700/50">
              <TableHead className="text-slate-300">{t('customContent.list.table.type')}</TableHead>
              <TableHead className="text-slate-300">{t('customContent.list.table.title')}</TableHead>
              <TableHead className="text-slate-300">{t('customContent.list.table.details')}</TableHead>
              <TableHead className="text-slate-300">{t('customContent.list.table.status')}</TableHead>
              <TableHead className="text-slate-300">{t('customContent.list.table.chunks')}</TableHead>
              <TableHead className="text-slate-300">{t('customContent.list.table.created')}</TableHead>
              <TableHead className="text-right text-slate-300">{t('customContent.list.table.actions')}</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {data.map((item) => (
              <TableRow key={item.id} className="border-slate-700 hover:bg-slate-700/30">
                <TableCell>
                  {item.contentType === "pdf_upload" ? (
                    <File className="h-4 w-4 text-red-400" />
                  ) : (
                    <FileText className="h-4 w-4 text-blue-400" />
                  )}
                </TableCell>
                <TableCell className="font-medium text-white">{item.title}</TableCell>
                <TableCell className="text-sm text-slate-400">
                  {item.contentType === "pdf_upload" ? (
                    <div>
                      <div>{item.originalFilename}</div>
                      <div>
                        {item.pageCount} {t('customContent.list.table.pages')} • {((item.fileSize || 0) / 1024).toFixed(0)} KB
                      </div>
                    </div>
                  ) : (
                    <div>{t('customContent.list.table.textEntry')}</div>
                  )}
                </TableCell>
                <TableCell>
                  <CustomContentStatusBadge
                    contentId={item.id}
                    status={item.syncStatus}
                    error={item.syncError}
                  />
                </TableCell>
                <TableCell className="text-slate-300">{item.chunkCount || 0}</TableCell>
                <TableCell className="text-slate-300">
                  {new Date(item.createdAt).toLocaleDateString()}
                </TableCell>
                <TableCell className="text-right">
                  <div className="flex gap-1 justify-end">
                    <Button
                      variant="ghost"
                      size="icon"
                      onClick={() => setViewContentId(item.id)}
                      className="text-slate-400 hover:text-cyan-400 hover:bg-slate-700"
                      title={t('customContent.list.view')}
                    >
                      <Eye className="h-4 w-4" />
                    </Button>
                    <Button
                      variant="ghost"
                      size="icon"
                      onClick={() => setDeleteId(item.id)}
                      className="text-slate-400 hover:text-red-400 hover:bg-slate-700"
                      title={t('customContent.list.delete.title')}
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>

      {/* Delete Confirmation Dialog */}
      <AlertDialog open={!!deleteId} onOpenChange={() => setDeleteId(null)}>
        <AlertDialogContent className="bg-slate-800 border-slate-700">
          <AlertDialogHeader>
            <AlertDialogTitle className="text-white">{t('customContent.list.delete.title')}</AlertDialogTitle>
            <AlertDialogDescription className="text-slate-400">
              {t('customContent.list.delete.description')}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel className="bg-slate-700 border-slate-600 text-white hover:bg-slate-600">
              {t('customContent.list.delete.cancel')}
            </AlertDialogCancel>
            <AlertDialogAction
              onClick={() => deleteId && handleDelete(deleteId)}
              className="bg-red-600 text-white hover:bg-red-700"
            >
              {t('customContent.list.delete.confirm')}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* Content Viewer Dialog */}
      {viewContentId && selectedShop && (
        <CustomContentViewer
          contentId={viewContentId}
          storeId={selectedShop.id}
          open={!!viewContentId}
          onOpenChange={(open) => !open && setViewContentId(null)}
        />
      )}
    </>
  );
}
