/**
 * AiDebugDialog Component
 *
 * Shows the AI validation prompt for debugging purposes with:
 * - Cost estimate with configurable cost per million tokens
 * - Processing time estimation
 * - Prompt sources display with colored badges
 * - Content parsed by markers into visual sections
 *
 * Only visible to users with admin:debug permission.
 */

import { useState } from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from '@/components/ui/dialog';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Loader2 } from 'lucide-react';
import type { AiDebugPromptResponse } from '../hooks/useAiValidation';

interface AiDebugDialogProps {
  open: boolean;
  onClose: () => void;
  debugData: AiDebugPromptResponse | null;
  isLoading?: boolean;
}

/**
 * Format estimated time for display
 */
const formatTime = (seconds: number | null | undefined): string => {
  if (!seconds) return 'Unknown';
  if (seconds < 60) return `~${Math.round(seconds)}s`;
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = Math.round(seconds % 60);
  return `~${minutes}m ${remainingSeconds}s`;
};

/**
 * Calculate cost estimate in cents
 */
const calculateCost = (promptLength: number, costPerMillion: number): string => {
  const estimatedTokens = Math.round(promptLength / 4);
  const costCents = (estimatedTokens / 1_000_000) * costPerMillion * 100;
  return costCents < 1 ? '<1¢' : `${costCents.toFixed(1)}¢`;
};

/**
 * Parse user message content into visual sections based on text markers
 */
const parseUserContent = (content: string) => {
  // 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 [{ type: 'default', 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 ends
  let taxonomyEndIndex = content.length;
  if (productDataStartIndex >= 0) {
    taxonomyEndIndex = productDataStartIndex;
  }

  const segments: Array<{ type: string; content: string }> = [];

  // General section (beginning to company/taxonomy/product)
  if (generalEndIndex > 0) {
    segments.push({
      type: 'general',
      content: content.substring(0, generalEndIndex),
    });
  }

  // Company-specific section if present
  if (companySpecificStartIndex >= 0 && companySpecificEndIndex >= 0) {
    segments.push({
      type: 'company',
      content: content.substring(
        companySpecificStartIndex,
        companySpecificEndIndex + '--- END COMPANY-SPECIFIC INSTRUCTIONS ---'.length
      ),
    });
  }

  // Taxonomy section
  if (actualTaxonomyStartIndex >= 0) {
    segments.push({
      type: 'taxonomy',
      content: content.substring(actualTaxonomyStartIndex, taxonomyEndIndex),
    });
  }

  // Product data section
  if (productDataStartIndex >= 0) {
    segments.push({
      type: 'product',
      content: content.substring(productDataStartIndex),
    });
  }

  return segments;
};

// Section styling configurations
const SECTION_STYLES = {
  system: {
    badge: 'bg-purple-100 hover:bg-purple-200 cursor-pointer',
    header: 'bg-purple-50 text-purple-800',
    content: 'bg-purple-50/30',
    border: 'border-purple-500',
    label: 'text-purple-700',
  },
  general: {
    badge: 'bg-green-100 hover:bg-green-200 cursor-pointer',
    header: 'bg-green-50 text-green-800',
    content: 'bg-green-50/30',
    border: 'border-green-500',
    label: 'text-green-700',
  },
  company: {
    badge: 'bg-blue-100 hover:bg-blue-200 cursor-pointer',
    header: 'bg-blue-50 text-blue-800',
    content: 'bg-blue-50/30',
    border: 'border-blue-500',
    label: 'text-blue-700',
  },
  taxonomy: {
    badge: 'bg-amber-100 hover:bg-amber-200 cursor-pointer',
    header: 'bg-amber-50 text-amber-800',
    content: 'bg-amber-50/30',
    border: 'border-amber-500',
    label: 'text-amber-700',
  },
  product: {
    badge: 'bg-pink-100 hover:bg-pink-200 cursor-pointer',
    header: 'bg-pink-50 text-pink-800',
    content: 'bg-pink-50/30',
    border: 'border-pink-500',
    label: 'text-pink-700',
  },
};

export const AiDebugDialog = ({
  open,
  onClose,
  debugData,
  isLoading = false,
}: AiDebugDialogProps) => {
  // Editable cost per million tokens (default to $1.25 for Claude)
  const [costPerMillion, setCostPerMillion] = useState(1.25);

  // Calculate prompt length and tokens
  const promptLength = debugData?.promptLength ?? 0;
  const estimatedTokens = Math.round(promptLength / 4);

  // Check if we have company prompts for badges
  const companyPrompts = debugData?.promptSources?.companyPrompts ?? [];

  // Scroll to section helper
  const scrollToSection = (id: string) => {
    document.getElementById(id)?.scrollIntoView({ behavior: 'smooth' });
  };

  return (
    <Dialog open={open} onOpenChange={(isOpen) => !isOpen && onClose()}>
      <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">
          {isLoading ? (
            <div className="flex items-center justify-center h-full">
              <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
            </div>
          ) : debugData ? (
            <>
              {/* Stats Cards */}
              <div className="flex-shrink-0 grid grid-cols-3 gap-4 mb-4">
                {/* Prompt Length Card */}
                <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.toLocaleString()}</span>
                      </div>
                      <div className="text-sm">
                        <span className="text-muted-foreground">Tokens:</span>{' '}
                        <span className="font-semibold">~{estimatedTokens.toLocaleString()}</span>
                      </div>
                    </div>
                  </CardContent>
                </Card>

                {/* Cost Estimate 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 className="text-sm text-muted-foreground">$</label>
                        <Input
                          type="number"
                          value={costPerMillion}
                          onChange={(e) => setCostPerMillion(Number(e.target.value) || 1.25)}
                          className="w-[50px] h-6 px-1 mx-1 text-sm"
                          min="0"
                          step="0.25"
                        />
                        <label className="text-sm text-muted-foreground">per million input tokens</label>
                      </div>
                      <div className="text-sm">
                        <span className="text-muted-foreground">Cost:</span>{' '}
                        <span className="font-semibold">
                          {calculateCost(promptLength, costPerMillion)}
                        </span>
                      </div>
                    </div>
                  </CardContent>
                </Card>

                {/* Processing Time 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">
                      {debugData.estimatedProcessingTime?.seconds ? (
                        <>
                          <div className="text-sm">
                            <span className="text-muted-foreground">Estimated time:</span>{' '}
                            <span className="font-semibold">
                              {formatTime(debugData.estimatedProcessingTime.seconds)}
                            </span>
                          </div>
                          <div className="text-xs text-muted-foreground">
                            Based on {debugData.estimatedProcessingTime.sampleCount} similar
                            validation{debugData.estimatedProcessingTime.sampleCount !== 1 ? 's' : ''}
                          </div>
                        </>
                      ) : (
                        <div className="text-sm text-muted-foreground">
                          No historical data available
                        </div>
                      )}
                    </div>
                  </CardContent>
                </Card>
              </div>

              {/* Prompt Sources Badges - Only show if we have apiFormat */}
              {debugData.apiFormat && (
                <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={SECTION_STYLES.system.badge}
                        onClick={() => scrollToSection('system-message')}
                      >
                        System
                      </Badge>
                      <Badge
                        variant="outline"
                        className={SECTION_STYLES.general.badge}
                        onClick={() => scrollToSection('general-section')}
                      >
                        General
                      </Badge>
                      {companyPrompts.map((cp, idx) => (
                        <Badge
                          key={idx}
                          variant="outline"
                          className={SECTION_STYLES.company.badge}
                          onClick={() => scrollToSection('company-section')}
                        >
                          {cp.companyName || `Company ${cp.company}`}
                        </Badge>
                      ))}
                      <Badge
                        variant="outline"
                        className={SECTION_STYLES.taxonomy.badge}
                        onClick={() => scrollToSection('taxonomy-section')}
                      >
                        Taxonomy
                      </Badge>
                      <Badge
                        variant="outline"
                        className={SECTION_STYLES.product.badge}
                        onClick={() => scrollToSection('product-section')}
                      >
                        Products
                      </Badge>
                    </div>
                  </CardContent>
                </Card>
              )}

              {/* Prompt Content */}
              <ScrollArea className="flex-1 w-full [&>div>div]:!overflow-x-hidden">
                {debugData.apiFormat ? (
                  // Render API format with parsed sections
                  debugData.apiFormat.map((message, idx) => (
                    <div key={idx} className="border rounded-md p-2 mb-4 overflow-hidden">
                      <div
                        id={message.role === 'system' ? 'system-message' : undefined}
                        className={`px-6 py-2 mb-2 rounded-sm font-medium ${
                          message.role === 'system'
                            ? SECTION_STYLES.system.header
                            : SECTION_STYLES.general.header
                        }`}
                      >
                        Role: {message.role}
                      </div>

                      <div
                        className={`p-4 overflow-hidden ${
                          message.role === 'system'
                            ? SECTION_STYLES.system.content
                            : SECTION_STYLES.general.content
                        }`}
                      >
                        {message.role === 'user' ? (
                          // Parse user message into visual sections
                          <div className="w-full overflow-hidden">
                            {parseUserContent(message.content).map((segment, segIdx) => {
                              const style = SECTION_STYLES[segment.type as keyof typeof SECTION_STYLES] || SECTION_STYLES.general;
                              const sectionId = segment.type === 'general' ? 'general-section'
                                : segment.type === 'company' ? 'company-section'
                                : segment.type === 'taxonomy' ? 'taxonomy-section'
                                : segment.type === 'product' ? 'product-section'
                                : undefined;

                              const sectionLabel = segment.type === 'general' ? 'General Prompt'
                                : segment.type === 'company' ? 'Company-Specific Instructions'
                                : segment.type === 'taxonomy' ? 'Taxonomy Data'
                                : segment.type === 'product' ? 'Product Data'
                                : undefined;

                              if (segment.type === 'default') {
                                return (
                                  <div
                                    key={segIdx}
                                    className="font-mono text-xs"
                                    style={{ whiteSpace: 'pre-wrap', wordBreak: 'break-word', overflowWrap: 'anywhere' }}
                                  >
                                    {segment.content}
                                  </div>
                                );
                              }

                              return (
                                <div
                                  key={segIdx}
                                  id={sectionId}
                                  className={`border-l-4 ${style.border} pl-4 py-2 my-2`}
                                  style={{ overflow: 'hidden' }}
                                >
                                  {sectionLabel && (
                                    <div className={`text-xs font-semibold ${style.label} mb-2`}>
                                      {sectionLabel}
                                    </div>
                                  )}
                                  <div
                                    className="font-mono text-xs"
                                    style={{ whiteSpace: 'pre-wrap', wordBreak: 'break-word', overflowWrap: 'anywhere' }}
                                  >
                                    {segment.content}
                                  </div>
                                </div>
                              );
                            })}
                          </div>
                        ) : (
                          // System message - show as-is
                          <div
                            className="font-mono text-xs"
                            style={{ whiteSpace: 'pre-wrap', wordBreak: 'break-word', overflowWrap: 'anywhere' }}
                          >
                            {message.content}
                          </div>
                        )}
                      </div>
                    </div>
                  ))
                ) : debugData.sampleFullPrompt ? (
                  // Fallback to sample full prompt
                  <div
                    className="p-4 font-mono text-xs"
                    style={{ whiteSpace: 'pre-wrap', wordBreak: 'break-word', overflowWrap: 'anywhere' }}
                  >
                    {debugData.sampleFullPrompt}
                  </div>
                ) : (
                  <div className="flex items-center justify-center h-full text-muted-foreground">
                    No prompt data available
                  </div>
                )}
              </ScrollArea>
            </>
          ) : (
            <div className="flex items-center justify-center h-full text-muted-foreground">
              No debug data available
            </div>
          )}
        </div>
      </DialogContent>
    </Dialog>
  );
};
