import React, { useState } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from "@/components/ui/dialog";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Button } from "@/components/ui/button";
import { Loader2, CheckIcon, XIcon } from "lucide-react";
import { Code } from "@/components/ui/code";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  AiValidationDetails,
  AiValidationProgress,
  CurrentPrompt,
} from "../hooks/useAiValidation";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";

interface TaxonomyStats {
  categories: number;
  themes: number;
  colors: number;
  taxCodes: number;
  sizeCategories: number;
  suppliers: number;
  companies: number;
  artists: number;
}

interface DebugData {
  taxonomyStats: TaxonomyStats | null;
  basePrompt: string;
  sampleFullPrompt: string;
  promptLength: number;
  apiFormat?: Array<{
    role: string;
    content: string;
  }>;
  promptSources?: {
    systemPrompt?: { id: number; prompt_text: string };
    generalPrompt?: { id: number; prompt_text: string };
    companyPrompts?: Array<{
      id: number;
      company: string;
      companyName?: string;
      prompt_text: string;
    }>;
  };
  estimatedProcessingTime?: {
    seconds: number | null;
    sampleCount: number;
  };
}

interface AiValidationDialogsProps {
  aiValidationProgress: AiValidationProgress;
  aiValidationDetails: AiValidationDetails;
  currentPrompt: CurrentPrompt;
  setAiValidationProgress: React.Dispatch<
    React.SetStateAction<AiValidationProgress>
  >;
  setAiValidationDetails: React.Dispatch<
    React.SetStateAction<AiValidationDetails>
  >;
  setCurrentPrompt: React.Dispatch<React.SetStateAction<CurrentPrompt>>;
  revertAiChange: (productIndex: number, fieldKey: string) => void;
  isChangeReverted: (productIndex: number, fieldKey: string) => boolean;
  getFieldDisplayValueWithHighlight: (
    fieldKey: string,
    originalValue: any,
    correctedValue: any
  ) => { originalHtml: string; correctedHtml: string };
  fields: readonly any[];
  debugData?: DebugData;
}

export const AiValidationDialogs: React.FC<AiValidationDialogsProps> = ({
  aiValidationProgress,
  aiValidationDetails,
  currentPrompt,
  setAiValidationProgress,
  setAiValidationDetails,
  setCurrentPrompt,
  revertAiChange,
  isChangeReverted,
  getFieldDisplayValueWithHighlight,
  fields,
}) => {
  const [costPerMillionTokens, setCostPerMillionTokens] = useState(2.5); // Default cost

  // Create our own state to track changes
  const [localReversionState, setLocalReversionState] = useState<
    Record<string, boolean>
  >({});

  // Initialize local state from the isChangeReverted function when component mounts
  // or when aiValidationDetails changes
  React.useEffect(() => {
    if (
      aiValidationDetails.changeDetails &&
      aiValidationDetails.changeDetails.length > 0
    ) {
      const initialState: Record<string, boolean> = {};

      aiValidationDetails.changeDetails.forEach((product) => {
        product.changes.forEach((change) => {
          const key = `${product.productIndex}-${change.field}`;
          initialState[key] = isChangeReverted(
            product.productIndex,
            change.field
          );
        });
      });

      setLocalReversionState(initialState);
    }
  }, [aiValidationDetails.changeDetails, isChangeReverted]);

  // This function will toggle the local state for a given change
  const toggleChangeAcceptance = (productIndex: number, fieldKey: string) => {
    const key = `${productIndex}-${fieldKey}`;
    const currentlyRejected = !!localReversionState[key];

    // Toggle the local state
    setLocalReversionState((prev) => ({
      ...prev,
      [key]: !prev[key],
    }));

    // Only call revertAiChange when toggling to rejected state
    // Since revertAiChange is specifically for rejecting changes
    if (!currentlyRejected) {
      revertAiChange(productIndex, fieldKey);
    }
  };

  // Function to check local reversion state
  const isChangeLocallyReverted = (
    productIndex: number,
    fieldKey: string
  ): boolean => {
    const key = `${productIndex}-${fieldKey}`;
    return !!localReversionState[key];
  };

  // Format time helper
  const formatTime = (seconds: number): string => {
    if (seconds < 60) {
      return `${Math.round(seconds)} seconds`;
    } else {
      const minutes = Math.floor(seconds / 60);
      const remainingSeconds = Math.round(seconds % 60);
      return `${minutes}m ${remainingSeconds}s`;
    }
  };

  // Calculate token costs
  const calculateTokenCost = (promptLength: number): number => {
    const estimatedTokens = Math.round(promptLength / 4);
    return (estimatedTokens / 1_000_000) * costPerMillionTokens * 100; // In cents
  };

  // Use the prompt length from the current prompt
  const promptLength = currentPrompt.prompt ? currentPrompt.prompt.length : 0;

  return (
    <>
      {/* Current Prompt Dialog with Debug Info */}
      <Dialog
        open={currentPrompt.isOpen}
        onOpenChange={(open) =>
          setCurrentPrompt((prev) => ({ ...prev, isOpen: open }))
        }
      >
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-hidden">
          <DialogHeader>
            <DialogTitle>Current AI Prompt</DialogTitle>
            <DialogDescription>
              This is the current prompt that would be sent to the AI for
              validation
            </DialogDescription>
          </DialogHeader>

          <div className="flex flex-col h-[calc(90vh-120px)] overflow-hidden">
            {/* Debug Information Section - Fixed at the top */}
            <div className="flex-shrink-0">
              {currentPrompt.isLoading ? (
                <div className="flex justify-center items-center h-[100px]"></div>
              ) : (
                <>
                  <div className="grid grid-cols-3 gap-4 mb-4">
                    <Card className="py-2">
                      <CardHeader className="py-2">
                        <CardTitle className="text-base">
                          Prompt Length
                        </CardTitle>
                      </CardHeader>
                      <CardContent className="py-2">
                        <div className="flex flex-col space-y-2">
                          <div className="text-sm">
                            <span className="text-muted-foreground">
                              Characters:
                            </span>{" "}
                            <span className="font-semibold">
                              {promptLength}
                            </span>
                          </div>
                          <div className="text-sm">
                            <span className="text-muted-foreground">
                              Tokens:
                            </span>{" "}
                            <span className="font-semibold">
                              ~{Math.round(promptLength / 4)}
                            </span>
                          </div>
                        </div>
                      </CardContent>
                    </Card>

                    <Card className="py-2">
                      <CardHeader className="py-2">
                        <CardTitle className="text-base">
                          Cost Estimate
                        </CardTitle>
                      </CardHeader>
                      <CardContent className="py-2">
                        <div className="flex flex-col space-y-2">
                          <div className="flex flex-row items-center">
                            <label
                              htmlFor="costPerMillion"
                              className="text-sm text-muted-foreground"
                            >
                              $
                            </label>
                            <input
                              id="costPerMillion"
                              className="w-[40px] px-1 border rounded-md text-sm"
                              defaultValue={costPerMillionTokens.toFixed(2)}
                              onChange={(e) => {
                                const value = parseFloat(e.target.value);
                                if (!isNaN(value)) {
                                  setCostPerMillionTokens(value);
                                }
                              }}
                            />
                            <label
                              htmlFor="costPerMillion"
                              className="text-sm text-muted-foreground ml-1"
                            >
                              per million input tokens
                            </label>
                          </div>
                          <div className="text-sm">
                            <span className="text-muted-foreground">Cost:</span>{" "}
                            <span className="font-semibold">
                              {calculateTokenCost(promptLength).toFixed(1)}¢
                            </span>
                          </div>
                        </div>
                      </CardContent>
                    </Card>

                    <Card className="py-2">
                      <CardHeader className="py-2">
                        <CardTitle className="text-base">
                          Processing Time
                        </CardTitle>
                      </CardHeader>
                      <CardContent className="py-2">
                        <div className="flex flex-col space-y-2">
                          {currentPrompt.debugData?.estimatedProcessingTime ? (
                            currentPrompt.debugData.estimatedProcessingTime
                              .seconds ? (
                              <>
                                <div className="text-sm">
                                  <span className="text-muted-foreground">
                                    Estimated time:
                                  </span>{" "}
                                  <span className="font-semibold">
                                    {formatTime(
                                      currentPrompt.debugData
                                        .estimatedProcessingTime.seconds
                                    )}
                                  </span>
                                </div>
                                <div className="text-xs text-muted-foreground">
                                  Based on{" "}
                                  {
                                    currentPrompt.debugData
                                      .estimatedProcessingTime.sampleCount
                                  }{" "}
                                  similar validation
                                  {currentPrompt.debugData
                                    .estimatedProcessingTime.sampleCount !== 1
                                    ? "s"
                                    : ""}
                                </div>
                              </>
                            ) : (
                              <div className="text-sm text-muted-foreground">
                                No historical data available for this prompt
                                size
                              </div>
                            )
                          ) : (
                            <div className="text-sm text-muted-foreground">
                              No processing time data available
                            </div>
                          )}
                        </div>
                      </CardContent>
                    </Card>
                  </div>
                </>
              )}
            </div>

            {/* Prompt Section - Scrollable content */}
            <div className="flex-1 min-h-0">
              {currentPrompt.isLoading ? (
                <div className="flex items-center justify-center h-full">
                  <Loader2 className="h-8 w-8 animate-spin" />
                </div>
              ) : (
                <>
                  {currentPrompt.debugData?.apiFormat ? (
                    <div className="flex flex-col h-full">
                      {/* Prompt Sources Card - Fixed at the top of the content area */}
                      <Card className="py-2 mb-4 flex-shrink-0">
                        <CardHeader className="py-2">
                          <CardTitle className="text-base">
                            Prompt Sources
                          </CardTitle>
                        </CardHeader>
                        <CardContent className="py-2">
                          <div className="flex flex-wrap gap-2">
                            <Badge
                              variant="outline"
                              className="bg-purple-100 hover:bg-purple-200 cursor-pointer"
                              onClick={() =>
                                document
                                  .getElementById("system-message")
                                  ?.scrollIntoView({ behavior: "smooth" })
                              }
                            >
                              System
                            </Badge>
                            <Badge
                              variant="outline"
                              className="bg-green-100 hover:bg-green-200 cursor-pointer"
                              onClick={() =>
                                document
                                  .getElementById("general-section")
                                  ?.scrollIntoView({ behavior: "smooth" })
                              }
                            >
                              General
                            </Badge>

                            {currentPrompt.debugData.promptSources?.companyPrompts?.map(
                              (company, idx) => (
                                <Badge
                                  key={idx}
                                  variant="outline"
                                  className="bg-blue-100 hover:bg-blue-200 cursor-pointer"
                                  onClick={() =>
                                    document
                                      .getElementById("company-section")
                                      ?.scrollIntoView({ behavior: "smooth" })
                                  }
                                >
                                  {company.companyName ||
                                    `Company ${company.company}`}
                                </Badge>
                              )
                            )}

                            <Badge
                              variant="outline"
                              className="bg-amber-100 hover:bg-amber-200 cursor-pointer"
                              onClick={() =>
                                document
                                  .getElementById("taxonomy-section")
                                  ?.scrollIntoView({ behavior: "smooth" })
                              }
                            >
                              Taxonomy
                            </Badge>
                            <Badge
                              variant="outline"
                              className="bg-pink-100 hover:bg-pink-200 cursor-pointer"
                              onClick={() =>
                                document
                                  .getElementById("product-section")
                                  ?.scrollIntoView({ behavior: "smooth" })
                              }
                            >
                              Products
                            </Badge>
                          </div>
                        </CardContent>
                      </Card>

                      <ScrollArea className="flex-1 w-full overflow-y-auto">
                        {currentPrompt.debugData.apiFormat.map(
                          (message, idx: number) => (
                            <div
                              key={idx}
                              className="border rounded-md p-2 mb-4"
                            >
                              <div
                                id={
                                  message.role === "system"
                                    ? "system-message"
                                    : ""
                                }
                                className={`p-2 mb-2 rounded-sm font-medium ${
                                  message.role === "system"
                                    ? "bg-purple-50 text-purple-800"
                                    : "bg-green-50 text-green-800"
                                }`}
                              >
                                Role: {message.role}
                              </div>

                              <Code
                                className={`whitespace-pre-wrap p-4 break-normal max-w-full ${
                                  message.role === "system"
                                    ? "bg-purple-50/30"
                                    : "bg-green-50/30"
                                }`}
                              >
                                {message.role === "user" ? (
                                  <div className="text-wrapper">
                                    {(() => {
                                      const content = message.content;

                                      // Find section boundaries by looking for specific markers
                                      const companySpecificStartIndex =
                                        content.indexOf(
                                          "--- COMPANY-SPECIFIC INSTRUCTIONS ---"
                                        );
                                      const companySpecificEndIndex =
                                        content.indexOf(
                                          "--- END COMPANY-SPECIFIC INSTRUCTIONS ---"
                                        );

                                      const taxonomyStartIndex =
                                        content.indexOf(
                                          "All Available Categories:"
                                        );
                                      const taxonomyFallbackStartIndex =
                                        content.indexOf(
                                          "Available Categories:"
                                        );
                                      const actualTaxonomyStartIndex =
                                        taxonomyStartIndex >= 0
                                          ? taxonomyStartIndex
                                          : taxonomyFallbackStartIndex;

                                      const productDataStartIndex =
                                        content.indexOf(
                                          "----------Here is the product data to validate----------"
                                        );

                                      // If we can't find any markers, just return the content as-is
                                      if (
                                        actualTaxonomyStartIndex < 0 &&
                                        productDataStartIndex < 0 &&
                                        companySpecificStartIndex < 0
                                      ) {
                                        return content;
                                      }

                                      // Determine section indices
                                      let generalEndIndex = content.length;

                                      if (companySpecificStartIndex >= 0) {
                                        generalEndIndex =
                                          companySpecificStartIndex;
                                      } else if (
                                        actualTaxonomyStartIndex >= 0
                                      ) {
                                        generalEndIndex =
                                          actualTaxonomyStartIndex;
                                      } else if (productDataStartIndex >= 0) {
                                        generalEndIndex = productDataStartIndex;
                                      }

                                      // Determine where taxonomy starts
                                      let taxonomyEndIndex = content.length;
                                      if (productDataStartIndex >= 0) {
                                        taxonomyEndIndex =
                                          productDataStartIndex;
                                      }

                                      // Segments to render with appropriate styling
                                      const segments = [];

                                      // General section (beginning to company/taxonomy/product)
                                      if (generalEndIndex > 0) {
                                        segments.push(
                                          <div
                                            id="general-section"
                                            key="general"
                                            className="border-l-4 border-green-500 pl-4 py-0 my-1"
                                          >
                                            <div className="text-xs font-semibold text-green-700 mb-2">
                                              General Prompt
                                            </div>
                                            <pre className="whitespace-pre-wrap">
                                              {content.substring(
                                                0,
                                                generalEndIndex
                                              )}
                                            </pre>
                                          </div>
                                        );
                                      }

                                      // Company-specific section if present
                                      if (
                                        companySpecificStartIndex >= 0 &&
                                        companySpecificEndIndex >= 0
                                      ) {
                                        segments.push(
                                          <div
                                            id="company-section"
                                            key="company"
                                            className="border-l-4 border-blue-500 pl-4 py-0 my-1"
                                          >
                                            <div className="text-xs font-semibold text-blue-700 mb-2">
                                              Company-Specific Instructions
                                            </div>
                                            <pre className="whitespace-pre-wrap">
                                              {content.substring(
                                                companySpecificStartIndex,
                                                companySpecificEndIndex +
                                                  "--- END COMPANY-SPECIFIC INSTRUCTIONS ---"
                                                    .length
                                              )}
                                            </pre>
                                          </div>
                                        );
                                      }

                                      // Taxonomy section
                                      if (actualTaxonomyStartIndex >= 0) {
                                        const taxEnd = taxonomyEndIndex;
                                        segments.push(
                                          <div
                                            id="taxonomy-section"
                                            key="taxonomy"
                                            className="border-l-4 border-amber-500 pl-4 py-0 my-1"
                                          >
                                            <div className="text-xs font-semibold text-amber-700 mb-2">
                                              Taxonomy Data
                                            </div>
                                            <pre className="whitespace-pre-wrap">
                                              {content.substring(
                                                actualTaxonomyStartIndex,
                                                taxEnd
                                              )}
                                            </pre>
                                          </div>
                                        );
                                      }

                                      // Product data section
                                      if (productDataStartIndex >= 0) {
                                        segments.push(
                                          <div
                                            id="product-section"
                                            key="product"
                                            className="border-l-4 border-pink-500 pl-4 py-0 my-1"
                                          >
                                            <div className="text-xs font-semibold text-pink-700 mb-2">
                                              Product Data
                                            </div>
                                            <pre className="whitespace-pre-wrap">
                                              {content.substring(
                                                productDataStartIndex
                                              )}
                                            </pre>
                                          </div>
                                        );
                                      }

                                      return <>{segments}</>;
                                    })()}
                                  </div>
                                ) : (
                                  <pre className="whitespace-pre-wrap">
                                    {message.content}
                                  </pre>
                                )}
                              </Code>
                            </div>
                          )
                        )}
                      </ScrollArea>
                    </div>
                  ) : (
                    <ScrollArea className="h-full w-full">
                      <Code className="whitespace-pre-wrap p-4 break-normal max-w-full">
                        {currentPrompt.prompt}
                      </Code>
                    </ScrollArea>
                  )}
                </>
              )}
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* AI Validation Progress Dialog */}
      <Dialog
        open={aiValidationProgress.isOpen}
        onOpenChange={(open) => {
          // Only allow closing if validation failed
          if (!open && aiValidationProgress.step === -1) {
            setAiValidationProgress((prev) => ({ ...prev, isOpen: false }));
          }
        }}
      >
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>AI Validation Progress</DialogTitle>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="flex items-center gap-4">
              <div className="flex-1">
                <div className="h-2 w-full bg-secondary rounded-full overflow-hidden">
                  <div
                    className="h-full bg-primary transition-all duration-500"
                    style={{
                      width: `${
                        aiValidationProgress.progressPercent !== undefined
                          ? Math.round(aiValidationProgress.progressPercent)
                          : Math.round((aiValidationProgress.step / 5) * 100)
                      }%`,
                      backgroundColor:
                        aiValidationProgress.step === -1
                          ? "var(--destructive)"
                          : undefined,
                    }}
                  />
                </div>
              </div>
              <div className="text-sm text-muted-foreground w-12 text-right">
                {aiValidationProgress.step === -1
                  ? "❌"
                  : `${
                      aiValidationProgress.progressPercent !== undefined
                        ? Math.round(aiValidationProgress.progressPercent)
                        : Math.round((aiValidationProgress.step / 5) * 100)
                    }%`}
              </div>
            </div>
            <p className="text-center text-sm text-muted-foreground">
              {aiValidationProgress.status}
            </p>
            {(() => {
              // Only show time remaining if we have an estimate and are in progress
              return (
                aiValidationProgress.estimatedSeconds &&
                aiValidationProgress.elapsedSeconds !== undefined &&
                aiValidationProgress.step > 0 &&
                aiValidationProgress.step < 5 && (
                  <div className="text-center text-sm">
                    {(() => {
                      // Calculate time remaining using the elapsed seconds
                      const elapsedSeconds =
                        aiValidationProgress.elapsedSeconds;
                      const totalEstimatedSeconds =
                        aiValidationProgress.estimatedSeconds;
                      const remainingSeconds = Math.max(
                        0,
                        totalEstimatedSeconds - elapsedSeconds
                      );

                      // Format time remaining
                      if (remainingSeconds < 60) {
                        return `Approximately ${Math.round(
                          remainingSeconds
                        )} seconds remaining`;
                      } else {
                        const minutes = Math.floor(remainingSeconds / 60);
                        const seconds = Math.round(remainingSeconds % 60);
                        return `Approximately ${minutes}m ${seconds}s remaining`;
                      }
                    })()}
                    {aiValidationProgress.promptLength && (
                      <p className="mt-1 text-xs text-muted-foreground">
                        Prompt length:{" "}
                        {aiValidationProgress.promptLength.toLocaleString()}{" "}
                        characters
                      </p>
                    )}
                  </div>
                )
              );
            })()}
          </div>
        </DialogContent>
      </Dialog>

      {/* AI Validation Results Dialog */}
      <Dialog
        open={aiValidationDetails.isOpen}
        onOpenChange={(open) =>
          setAiValidationDetails((prev) => ({ ...prev, isOpen: open }))
        }
      >
        <DialogContent className="max-w-6xl w-[90vw]">
          <DialogHeader>
            <DialogTitle>AI Validation Results</DialogTitle>
            <DialogDescription>
              Review the changes and warnings suggested by the AI
            </DialogDescription>
          </DialogHeader>
          <ScrollArea className="max-h-[70vh]">
            {aiValidationDetails.changeDetails &&
            aiValidationDetails.changeDetails.length > 0 ? (
              <div className="mb-6 space-y-6">
                <h3 className="font-semibold text-lg">Detailed Changes:</h3>
                {aiValidationDetails.changeDetails.map((product, i) => {
                  // Find the title change if it exists
                  const titleChange = product.changes.find(
                    (c) => c.field === "title"
                  );
                  const titleValue = titleChange
                    ? titleChange.corrected
                    : product.title;

                  return (
                    <div key={`product-${i}`} className="border rounded-md p-4">
                      <h4 className="font-medium text-base mb-3">
                        {titleValue || `Product ${product.productIndex + 1}`}
                      </h4>
                      <Table>
                        <TableHeader>
                          <TableRow>
                            <TableHead className="">Field</TableHead>
                            <TableHead className="w-[35%]">
                              Original Value
                            </TableHead>
                            <TableHead className="w-[35%]">
                              Corrected Value
                            </TableHead>
                            <TableHead className="text-right">
                              Accept Changes?
                            </TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {product.changes.map((change, j) => {
                            const field = fields.find(
                              (f) => f.key === change.field
                            );
                            const fieldLabel = field
                              ? field.label
                              : change.field;
                            const isReverted = isChangeLocallyReverted(
                              product.productIndex,
                              change.field
                            );

                            // Get highlighted differences
                            const { originalHtml, correctedHtml } =
                              getFieldDisplayValueWithHighlight(
                                change.field,
                                change.original,
                                change.corrected
                              );

                            return (
                              <TableRow key={`change-${j}`}>
                                <TableCell className="font-medium">
                                  {fieldLabel}
                                </TableCell>
                                <TableCell>
                                  <div
                                    dangerouslySetInnerHTML={{
                                      __html: originalHtml,
                                    }}
                                  />
                                </TableCell>
                                <TableCell>
                                  <div
                                    dangerouslySetInnerHTML={{
                                      __html: correctedHtml,
                                    }}
                                  />
                                </TableCell>
                                <TableCell className="text-right align-top">
                                  <div className="flex justify-end gap-2">
                                    <Button
                                      variant="outline"
                                      size="sm"
                                      onClick={() => {
                                        // Toggle to Accepted state if currently rejected
                                        toggleChangeAcceptance(
                                          product.productIndex,
                                          change.field
                                        );
                                      }}
                                      className={
                                        !isReverted
                                          ? "bg-green-100 text-green-600 border-green-300 flex items-center"
                                          : "border-gray-200 text-gray-600 hover:bg-green-50 hover:text-green-600 hover:border-green-200 flex items-center"
                                      }
                                    >
                                      <CheckIcon className="h-4 w-4" />
                                    </Button>
                                    <Button
                                      variant="outline"
                                      size="sm"
                                      onClick={() => {
                                        // Toggle to Rejected state if currently accepted
                                        toggleChangeAcceptance(
                                          product.productIndex,
                                          change.field
                                        );
                                      }}
                                      className={
                                        isReverted
                                          ? "bg-red-100 text-red-600 border-red-300 flex items-center"
                                          : "border-gray-200 text-gray-600 hover:bg-red-50 hover:text-red-600 hover:border-red-200 flex items-center"
                                      }
                                    >
                                      <XIcon className="h-4 w-4" />
                                    </Button>
                                  </div>
                                </TableCell>
                              </TableRow>
                            );
                          })}
                        </TableBody>
                      </Table>
                    </div>
                  );
                })}
              </div>
            ) : (
              <div className="py-8 text-center text-muted-foreground">
                {aiValidationDetails.warnings &&
                aiValidationDetails.warnings.length > 0 ? (
                  <div>
                    <p className="mb-4">
                      No changes were made, but the AI provided some warnings:
                    </p>
                    <ul className="list-disc pl-8 text-left">
                      {aiValidationDetails.warnings.map((warning, i) => (
                        <li key={`warning-${i}`} className="mb-2">
                          {warning}
                        </li>
                      ))}
                    </ul>
                  </div>
                ) : (
                  <p>No changes or warnings were suggested by the AI.</p>
                )}
              </div>
            )}
          </ScrollArea>
        </DialogContent>
      </Dialog>
    </>
  );
};
