'use client';

import { useState, useCallback, useMemo } from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Progress } from '@/components/ui/progress';
import { Separator } from '@/components/ui/separator';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Switch } from '@/components/ui/switch';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import {
  Upload,
  Download,
  Settings,
  Wand2,
  CheckCircle2,
  XCircle,
  AlertTriangle,
  Info,
  ChevronRight,
  RefreshCw,
  Sparkles,
  Users,
  Box,
  Gamepad2,
  Glasses,
  PartyPopper,
  Globe,
  Cpu,
  Heart,
  Landmark,
  Headphones,
  ArrowLeftRight,
  FileType,
  Bone,
  Layers,
  ImageIcon,
  FileBox,
  Zap,
} from 'lucide-react';

import {
  AvatarPlatformId,
  avatarPlatforms,
  supportedPlatforms,
  getConstraintsForPlatform,
} from '@/lib/avatar-platforms';
import {
  AvatarFileFormat,
  ParsedAvatar,
  AvatarValidationResult,
  ExportOptions,
  FORMAT_SPECS,
  getSupportedImportFormats,
  getSupportedExportFormats,
  validateForPlatform,
  createDemoAvatar,
  generateExportFilename,
  getOptimizationRecommendations,
} from '@/lib/avatar-formats';
import {
  getConversionPaths,
  calculatePlatformCompatibility,
} from '@/lib/avatar-rigging';
import {
  avatarTemplates,
  platformPresets,
  getTemplatesForPlatform,
  getPresetsForPlatform,
  AvatarTemplate,
  AvatarPreset,
} from '@/lib/templates-avatars';

interface AvatarToolkitProps {
  isOpen: boolean;
  onClose: () => void;
}

type TabValue = 'import' | 'export' | 'convert' | 'templates' | 'validate';

// Platform icon mapping
const platformIcons: Record<AvatarPlatformId, React.ReactNode> = {
  roblox: <Gamepad2 className="h-4 w-4" />,
  vrchat: <Glasses className="h-4 w-4" />,
  recroom: <PartyPopper className="h-4 w-4" />,
  spatial: <Globe className="h-4 w-4" />,
  sandbox: <Box className="h-4 w-4" />,
  neos: <Cpu className="h-4 w-4" />,
  resonite: <Sparkles className="h-4 w-4" />,
  chilloutvr: <Heart className="h-4 w-4" />,
  decentraland: <Landmark className="h-4 w-4" />,
  'meta-horizon': <Headphones className="h-4 w-4" />,
  universal: <Sparkles className="h-4 w-4" />,
};

export default function AvatarToolkit({ isOpen, onClose }: AvatarToolkitProps) {
  const [activeTab, setActiveTab] = useState<TabValue>('import');
  const [selectedPlatform, setSelectedPlatform] = useState<AvatarPlatformId>('universal');
  const [importedAvatar, setImportedAvatar] = useState<ParsedAvatar | null>(null);
  const [validationResult, setValidationResult] = useState<AvatarValidationResult | null>(null);
  const [isProcessing, setIsProcessing] = useState(false);
  const [processingProgress, setProcessingProgress] = useState(0);
  const [selectedTemplate, setSelectedTemplate] = useState<AvatarTemplate | null>(null);
  const [selectedPreset, setSelectedPreset] = useState<AvatarPreset | null>(null);

  // Export options state
  const [exportOptions, setExportOptions] = useState<Partial<ExportOptions>>({
    optimizeForPlatform: true,
    embedTextures: true,
    compressTextures: true,
    preserveBlendShapes: true,
    preserveAnimations: true,
    generateLODs: false,
  });

  // Conversion state
  const [sourcePlatform, setSourcePlatform] = useState<AvatarPlatformId>('universal');
  const [targetPlatform, setTargetPlatform] = useState<AvatarPlatformId>('vrchat');

  // Handle file import
  const handleFileImport = useCallback(async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    setIsProcessing(true);
    setProcessingProgress(0);

    // Simulate file processing with progress
    const progressInterval = setInterval(() => {
      setProcessingProgress((prev) => Math.min(prev + 10, 90));
    }, 200);

    try {
      // In a real implementation, this would parse the actual file
      // For demo purposes, we create a mock avatar
      await new Promise((resolve) => setTimeout(resolve, 2000));

      const demoAvatar = createDemoAvatar(file.name.replace(/\.[^.]+$/, ''), selectedPlatform);
      setImportedAvatar(demoAvatar);

      // Validate against selected platform
      const validation = validateForPlatform(demoAvatar, selectedPlatform);
      setValidationResult(validation);

      setProcessingProgress(100);
    } catch (error) {
      console.error('Import error:', error);
    } finally {
      clearInterval(progressInterval);
      setIsProcessing(false);
    }
  }, [selectedPlatform]);

  // Handle export
  const handleExport = useCallback(async () => {
    if (!importedAvatar) return;

    setIsProcessing(true);
    setProcessingProgress(0);

    const progressInterval = setInterval(() => {
      setProcessingProgress((prev) => Math.min(prev + 15, 90));
    }, 200);

    try {
      await new Promise((resolve) => setTimeout(resolve, 1500));

      const format = avatarPlatforms[selectedPlatform].exportFormat as AvatarFileFormat;
      const filename = generateExportFilename(importedAvatar.metadata.name, selectedPlatform, format);

      // Create a demo export blob
      const exportData = JSON.stringify({
        avatar: importedAvatar,
        platform: selectedPlatform,
        options: exportOptions,
        exportedAt: new Date().toISOString(),
      }, null, 2);

      const blob = new Blob([exportData], { type: 'application/json' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = filename.replace(/\.[^.]+$/, '.json'); // Demo uses JSON
      a.click();
      URL.revokeObjectURL(url);

      setProcessingProgress(100);
    } catch (error) {
      console.error('Export error:', error);
    } finally {
      clearInterval(progressInterval);
      setIsProcessing(false);
    }
  }, [importedAvatar, selectedPlatform, exportOptions]);

  // Get conversion paths
  const conversionPaths = useMemo(() => {
    return getConversionPaths(sourcePlatform);
  }, [sourcePlatform]);

  // Get templates for selected platform
  const platformTemplates = useMemo(() => {
    return getTemplatesForPlatform(selectedPlatform);
  }, [selectedPlatform]);

  // Get presets for selected platform
  const platformPresetsList = useMemo(() => {
    return getPresetsForPlatform(selectedPlatform);
  }, [selectedPlatform]);

  // Apply preset settings
  const applyPreset = useCallback((preset: AvatarPreset) => {
    setSelectedPreset(preset);
    setExportOptions({
      ...exportOptions,
      optimizeForPlatform: true,
      preserveBlendShapes: preset.settings.preserveBlendShapes,
      generateLODs: preset.settings.generateLODs,
    });
  }, [exportOptions]);

  return (
    <Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
      <DialogContent className="max-w-5xl max-h-[85vh] flex flex-col">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Sparkles className="h-5 w-5 text-primary" />
            AeThex Avatar Toolkit
          </DialogTitle>
          <DialogDescription>
            Import, export, and convert avatars across platforms like Roblox, VRChat, RecRoom, Spatial, and more
          </DialogDescription>
        </DialogHeader>

        <Tabs value={activeTab} onValueChange={(v) => setActiveTab(v as TabValue)} className="flex-1 flex flex-col min-h-0">
          <TabsList className="grid grid-cols-5 w-full">
            <TabsTrigger value="import" className="flex items-center gap-1.5">
              <Upload className="h-4 w-4" />
              Import
            </TabsTrigger>
            <TabsTrigger value="export" className="flex items-center gap-1.5">
              <Download className="h-4 w-4" />
              Export
            </TabsTrigger>
            <TabsTrigger value="convert" className="flex items-center gap-1.5">
              <ArrowLeftRight className="h-4 w-4" />
              Convert
            </TabsTrigger>
            <TabsTrigger value="templates" className="flex items-center gap-1.5">
              <Users className="h-4 w-4" />
              Templates
            </TabsTrigger>
            <TabsTrigger value="validate" className="flex items-center gap-1.5">
              <CheckCircle2 className="h-4 w-4" />
              Validate
            </TabsTrigger>
          </TabsList>

          <div className="flex-1 min-h-0 mt-4">
            {/* Import Tab */}
            <TabsContent value="import" className="h-full m-0">
              <div className="grid grid-cols-2 gap-6 h-full">
                <div className="space-y-4">
                  <div>
                    <Label className="text-sm font-medium">Target Platform</Label>
                    <Select value={selectedPlatform} onValueChange={(v) => setSelectedPlatform(v as AvatarPlatformId)}>
                      <SelectTrigger className="mt-1.5">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        {supportedPlatforms.map((platform) => (
                          <SelectItem key={platform.id} value={platform.id}>
                            <div className="flex items-center gap-2">
                              {platformIcons[platform.id]}
                              <span>{platform.displayName}</span>
                              {platform.status === 'beta' && (
                                <Badge variant="secondary" className="text-xs">Beta</Badge>
                              )}
                            </div>
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>

                  <div className="border-2 border-dashed rounded-lg p-8 text-center">
                    <input
                      type="file"
                      accept=".glb,.gltf,.fbx,.vrm,.obj,.pmx"
                      onChange={handleFileImport}
                      className="hidden"
                      id="avatar-import"
                      disabled={isProcessing}
                    />
                    <label htmlFor="avatar-import" className="cursor-pointer">
                      <Upload className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
                      <p className="font-medium">Drop your avatar file here</p>
                      <p className="text-sm text-muted-foreground mt-1">
                        Supports GLB, GLTF, FBX, VRM, OBJ, PMX
                      </p>
                      <Button variant="outline" className="mt-4" disabled={isProcessing}>
                        Browse Files
                      </Button>
                    </label>
                  </div>

                  {isProcessing && (
                    <div className="space-y-2">
                      <div className="flex items-center justify-between text-sm">
                        <span>Processing...</span>
                        <span>{processingProgress}%</span>
                      </div>
                      <Progress value={processingProgress} />
                    </div>
                  )}

                  <div>
                    <Label className="text-sm font-medium">Supported Formats</Label>
                    <div className="flex flex-wrap gap-2 mt-2">
                      {getSupportedImportFormats().map((format) => (
                        <Badge key={format} variant="outline">
                          {FORMAT_SPECS[format].extension}
                        </Badge>
                      ))}
                    </div>
                  </div>
                </div>

                <div className="space-y-4">
                  <h4 className="font-medium">Platform Requirements</h4>
                  {selectedPlatform && (
                    <div className="space-y-3 text-sm">
                      {(() => {
                        const constraints = getConstraintsForPlatform(selectedPlatform);
                        const platform = avatarPlatforms[selectedPlatform];
                        return (
                          <>
                            <div className="flex items-center justify-between p-2 bg-muted/50 rounded">
                              <span className="flex items-center gap-2">
                                <Layers className="h-4 w-4" /> Max Polygons
                              </span>
                              <span className="font-mono">{constraints.maxPolygons.toLocaleString()}</span>
                            </div>
                            <div className="flex items-center justify-between p-2 bg-muted/50 rounded">
                              <span className="flex items-center gap-2">
                                <Bone className="h-4 w-4" /> Max Bones
                              </span>
                              <span className="font-mono">{constraints.maxBones}</span>
                            </div>
                            <div className="flex items-center justify-between p-2 bg-muted/50 rounded">
                              <span className="flex items-center gap-2">
                                <Box className="h-4 w-4" /> Max Materials
                              </span>
                              <span className="font-mono">{constraints.maxMaterials}</span>
                            </div>
                            <div className="flex items-center justify-between p-2 bg-muted/50 rounded">
                              <span className="flex items-center gap-2">
                                <ImageIcon className="h-4 w-4" /> Max Texture Size
                              </span>
                              <span className="font-mono">{constraints.maxTextureSize}px</span>
                            </div>
                            <div className="flex items-center justify-between p-2 bg-muted/50 rounded">
                              <span className="flex items-center gap-2">
                                <FileBox className="h-4 w-4" /> Max File Size
                              </span>
                              <span className="font-mono">{constraints.maxFileSize}MB</span>
                            </div>
                            <Separator />
                            <div>
                              <span className="font-medium">Supported Features:</span>
                              <div className="flex flex-wrap gap-1.5 mt-2">
                                {platform.features.map((feature) => (
                                  <Badge key={feature} variant="secondary" className="text-xs">
                                    {feature}
                                  </Badge>
                                ))}
                              </div>
                            </div>
                          </>
                        );
                      })()}
                    </div>
                  )}
                </div>
              </div>
            </TabsContent>

            {/* Export Tab */}
            <TabsContent value="export" className="h-full m-0">
              <ScrollArea className="h-[400px]">
                <div className="grid grid-cols-2 gap-6 pr-4">
                  <div className="space-y-4">
                    <div>
                      <Label className="text-sm font-medium">Export Platform</Label>
                      <Select value={selectedPlatform} onValueChange={(v) => setSelectedPlatform(v as AvatarPlatformId)}>
                        <SelectTrigger className="mt-1.5">
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          {supportedPlatforms.map((platform) => (
                            <SelectItem key={platform.id} value={platform.id}>
                              <div className="flex items-center gap-2">
                                {platformIcons[platform.id]}
                                <span>{platform.displayName}</span>
                              </div>
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>

                    <div>
                      <Label className="text-sm font-medium">Export Preset</Label>
                      <Select
                        value={selectedPreset?.id || ''}
                        onValueChange={(v) => {
                          const preset = platformPresetsList.find((p) => p.id === v);
                          if (preset) applyPreset(preset);
                        }}
                      >
                        <SelectTrigger className="mt-1.5">
                          <SelectValue placeholder="Select a preset..." />
                        </SelectTrigger>
                        <SelectContent>
                          {platformPresetsList.map((preset) => (
                            <SelectItem key={preset.id} value={preset.id}>
                              <div>
                                <div className="font-medium">{preset.name}</div>
                                <div className="text-xs text-muted-foreground">{preset.description}</div>
                              </div>
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>

                    <Separator />

                    <div className="space-y-3">
                      <h4 className="font-medium text-sm">Export Options</h4>

                      <div className="flex items-center justify-between">
                        <Label htmlFor="optimize" className="text-sm">Optimize for Platform</Label>
                        <Switch
                          id="optimize"
                          checked={exportOptions.optimizeForPlatform}
                          onCheckedChange={(v) => setExportOptions({ ...exportOptions, optimizeForPlatform: v })}
                        />
                      </div>

                      <div className="flex items-center justify-between">
                        <Label htmlFor="embed" className="text-sm">Embed Textures</Label>
                        <Switch
                          id="embed"
                          checked={exportOptions.embedTextures}
                          onCheckedChange={(v) => setExportOptions({ ...exportOptions, embedTextures: v })}
                        />
                      </div>

                      <div className="flex items-center justify-between">
                        <Label htmlFor="compress" className="text-sm">Compress Textures</Label>
                        <Switch
                          id="compress"
                          checked={exportOptions.compressTextures}
                          onCheckedChange={(v) => setExportOptions({ ...exportOptions, compressTextures: v })}
                        />
                      </div>

                      <div className="flex items-center justify-between">
                        <Label htmlFor="blendshapes" className="text-sm">Preserve Blend Shapes</Label>
                        <Switch
                          id="blendshapes"
                          checked={exportOptions.preserveBlendShapes}
                          onCheckedChange={(v) => setExportOptions({ ...exportOptions, preserveBlendShapes: v })}
                        />
                      </div>

                      <div className="flex items-center justify-between">
                        <Label htmlFor="animations" className="text-sm">Preserve Animations</Label>
                        <Switch
                          id="animations"
                          checked={exportOptions.preserveAnimations}
                          onCheckedChange={(v) => setExportOptions({ ...exportOptions, preserveAnimations: v })}
                        />
                      </div>

                      <div className="flex items-center justify-between">
                        <Label htmlFor="lods" className="text-sm">Generate LODs</Label>
                        <Switch
                          id="lods"
                          checked={exportOptions.generateLODs}
                          onCheckedChange={(v) => setExportOptions({ ...exportOptions, generateLODs: v })}
                        />
                      </div>
                    </div>
                  </div>

                  <div className="space-y-4">
                    {importedAvatar ? (
                      <>
                        <div className="p-4 border rounded-lg">
                          <h4 className="font-medium mb-3">Avatar Preview</h4>
                          <div className="space-y-2 text-sm">
                            <div className="flex justify-between">
                              <span className="text-muted-foreground">Name:</span>
                              <span className="font-medium">{importedAvatar.metadata.name}</span>
                            </div>
                            <div className="flex justify-between">
                              <span className="text-muted-foreground">Triangles:</span>
                              <span className="font-mono">{importedAvatar.stats.totalTriangles.toLocaleString()}</span>
                            </div>
                            <div className="flex justify-between">
                              <span className="text-muted-foreground">Bones:</span>
                              <span className="font-mono">{importedAvatar.stats.totalBones}</span>
                            </div>
                            <div className="flex justify-between">
                              <span className="text-muted-foreground">Materials:</span>
                              <span className="font-mono">{importedAvatar.stats.totalMaterials}</span>
                            </div>
                            <div className="flex justify-between">
                              <span className="text-muted-foreground">Blend Shapes:</span>
                              <span className="font-mono">{importedAvatar.stats.totalBlendShapes}</span>
                            </div>
                          </div>
                        </div>

                        <div className="flex gap-2">
                          <Button onClick={handleExport} disabled={isProcessing} className="flex-1">
                            <Download className="h-4 w-4 mr-2" />
                            Export for {avatarPlatforms[selectedPlatform].name}
                          </Button>
                        </div>

                        {isProcessing && (
                          <Progress value={processingProgress} />
                        )}
                      </>
                    ) : (
                      <div className="flex flex-col items-center justify-center h-full text-center p-8 border-2 border-dashed rounded-lg">
                        <Upload className="h-12 w-12 text-muted-foreground mb-4" />
                        <p className="text-muted-foreground">
                          Import an avatar first to enable export options
                        </p>
                        <Button
                          variant="outline"
                          className="mt-4"
                          onClick={() => setActiveTab('import')}
                        >
                          Go to Import
                        </Button>
                      </div>
                    )}
                  </div>
                </div>
              </ScrollArea>
            </TabsContent>

            {/* Convert Tab */}
            <TabsContent value="convert" className="h-full m-0">
              <div className="grid grid-cols-3 gap-6">
                <div className="space-y-4">
                  <div>
                    <Label className="text-sm font-medium">Source Platform</Label>
                    <Select value={sourcePlatform} onValueChange={(v) => setSourcePlatform(v as AvatarPlatformId)}>
                      <SelectTrigger className="mt-1.5">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        {supportedPlatforms.map((platform) => (
                          <SelectItem key={platform.id} value={platform.id}>
                            <div className="flex items-center gap-2">
                              {platformIcons[platform.id]}
                              <span>{platform.displayName}</span>
                            </div>
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>

                  <div className="text-center py-4">
                    <ArrowLeftRight className="h-8 w-8 mx-auto text-muted-foreground" />
                  </div>

                  <div>
                    <Label className="text-sm font-medium">Target Platform</Label>
                    <Select value={targetPlatform} onValueChange={(v) => setTargetPlatform(v as AvatarPlatformId)}>
                      <SelectTrigger className="mt-1.5">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        {supportedPlatforms.map((platform) => (
                          <SelectItem key={platform.id} value={platform.id}>
                            <div className="flex items-center gap-2">
                              {platformIcons[platform.id]}
                              <span>{platform.displayName}</span>
                            </div>
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>

                  <div className="p-4 bg-muted/50 rounded-lg">
                    <div className="text-sm font-medium mb-2">Compatibility Score</div>
                    <div className="text-3xl font-bold text-primary">
                      {calculatePlatformCompatibility(sourcePlatform, targetPlatform)}%
                    </div>
                  </div>
                </div>

                <div className="col-span-2">
                  <h4 className="font-medium mb-3">Conversion Paths from {avatarPlatforms[sourcePlatform].name}</h4>
                  <ScrollArea className="h-[350px]">
                    <div className="space-y-2 pr-4">
                      {conversionPaths.map((path) => (
                        <div
                          key={path.target}
                          className={`p-3 border rounded-lg cursor-pointer transition-colors ${
                            path.target === targetPlatform
                              ? 'border-primary bg-primary/5'
                              : 'hover:bg-muted/50'
                          }`}
                          onClick={() => setTargetPlatform(path.target)}
                        >
                          <div className="flex items-center justify-between mb-2">
                            <div className="flex items-center gap-2">
                              {platformIcons[path.target]}
                              <span className="font-medium">{avatarPlatforms[path.target].displayName}</span>
                            </div>
                            <Badge variant={path.compatibility >= 80 ? 'default' : path.compatibility >= 60 ? 'secondary' : 'outline'}>
                              {path.compatibility}% compatible
                            </Badge>
                          </div>
                          {path.warnings.length > 0 && (
                            <div className="space-y-1">
                              {path.warnings.map((warning, i) => (
                                <div key={i} className="flex items-center gap-1.5 text-xs text-muted-foreground">
                                  <AlertTriangle className="h-3 w-3 text-yellow-500" />
                                  {warning}
                                </div>
                              ))}
                            </div>
                          )}
                        </div>
                      ))}
                    </div>
                  </ScrollArea>
                </div>
              </div>
            </TabsContent>

            {/* Templates Tab */}
            <TabsContent value="templates" className="h-full m-0">
              <div className="space-y-4">
                <div className="flex items-center gap-4">
                  <div className="flex-1">
                    <Input placeholder="Search templates..." />
                  </div>
                  <Select value={selectedPlatform} onValueChange={(v) => setSelectedPlatform(v as AvatarPlatformId)}>
                    <SelectTrigger className="w-[200px]">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      {supportedPlatforms.map((platform) => (
                        <SelectItem key={platform.id} value={platform.id}>
                          <div className="flex items-center gap-2">
                            {platformIcons[platform.id]}
                            <span>{platform.name}</span>
                          </div>
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                <ScrollArea className="h-[350px]">
                  <div className="grid grid-cols-3 gap-4 pr-4">
                    {(selectedPlatform === 'universal' ? avatarTemplates : platformTemplates).map((template) => (
                      <div
                        key={template.id}
                        className={`p-4 border rounded-lg cursor-pointer transition-all ${
                          selectedTemplate?.id === template.id
                            ? 'border-primary ring-2 ring-primary/20'
                            : 'hover:border-primary/50'
                        }`}
                        onClick={() => setSelectedTemplate(template)}
                      >
                        <div className="aspect-square bg-muted rounded mb-3 flex items-center justify-center">
                          <Users className="h-12 w-12 text-muted-foreground" />
                        </div>
                        <h4 className="font-medium text-sm">{template.name}</h4>
                        <p className="text-xs text-muted-foreground mt-1 line-clamp-2">
                          {template.description}
                        </p>
                        <div className="flex flex-wrap gap-1 mt-2">
                          <Badge variant="outline" className="text-xs">{template.style}</Badge>
                          <Badge variant="outline" className="text-xs">{template.polyCount} poly</Badge>
                        </div>
                        <div className="flex gap-1 mt-2">
                          {template.platforms.slice(0, 3).map((p) => (
                            <span key={p} className="text-muted-foreground">
                              {platformIcons[p]}
                            </span>
                          ))}
                          {template.platforms.length > 3 && (
                            <span className="text-xs text-muted-foreground">+{template.platforms.length - 3}</span>
                          )}
                        </div>
                      </div>
                    ))}
                  </div>
                </ScrollArea>

                {selectedTemplate && (
                  <div className="p-4 border rounded-lg bg-muted/30">
                    <div className="flex items-start justify-between">
                      <div>
                        <h4 className="font-medium">{selectedTemplate.name}</h4>
                        <p className="text-sm text-muted-foreground mt-1">{selectedTemplate.description}</p>
                      </div>
                      <Button size="sm">
                        <Download className="h-4 w-4 mr-1.5" />
                        Use Template
                      </Button>
                    </div>
                    <div className="flex flex-wrap gap-1.5 mt-3">
                      {selectedTemplate.features.map((feature) => (
                        <Badge key={feature} variant="secondary" className="text-xs">{feature}</Badge>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            </TabsContent>

            {/* Validate Tab */}
            <TabsContent value="validate" className="h-full m-0">
              <div className="grid grid-cols-2 gap-6">
                <div className="space-y-4">
                  <div>
                    <Label className="text-sm font-medium">Validation Target</Label>
                    <Select value={selectedPlatform} onValueChange={(v) => setSelectedPlatform(v as AvatarPlatformId)}>
                      <SelectTrigger className="mt-1.5">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        {supportedPlatforms.map((platform) => (
                          <SelectItem key={platform.id} value={platform.id}>
                            <div className="flex items-center gap-2">
                              {platformIcons[platform.id]}
                              <span>{platform.displayName}</span>
                            </div>
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>

                  {!importedAvatar ? (
                    <div className="border-2 border-dashed rounded-lg p-8 text-center">
                      <Wand2 className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
                      <p className="text-muted-foreground">
                        Import an avatar to validate it against platform requirements
                      </p>
                      <Button variant="outline" className="mt-4" onClick={() => setActiveTab('import')}>
                        Import Avatar
                      </Button>
                    </div>
                  ) : (
                    <div className="space-y-3">
                      <Button
                        onClick={() => {
                          const validation = validateForPlatform(importedAvatar, selectedPlatform);
                          setValidationResult(validation);
                        }}
                        className="w-full"
                      >
                        <RefreshCw className="h-4 w-4 mr-2" />
                        Validate for {avatarPlatforms[selectedPlatform].name}
                      </Button>

                      {validationResult && (
                        <div className="p-4 border rounded-lg">
                          <div className="flex items-center justify-between mb-4">
                            <div className="flex items-center gap-2">
                              {validationResult.isValid ? (
                                <CheckCircle2 className="h-5 w-5 text-green-500" />
                              ) : (
                                <XCircle className="h-5 w-5 text-red-500" />
                              )}
                              <span className="font-medium">
                                {validationResult.isValid ? 'Compatible' : 'Issues Found'}
                              </span>
                            </div>
                            <Badge variant={validationResult.score >= 80 ? 'default' : validationResult.score >= 50 ? 'secondary' : 'destructive'}>
                              Score: {validationResult.score}%
                            </Badge>
                          </div>

                          <div className="space-y-2">
                            {Object.entries(validationResult.constraints).map(([key, value]) => (
                              <div key={key} className="flex items-center justify-between text-sm">
                                <span className="capitalize">{key.replace(/([A-Z])/g, ' $1').trim()}</span>
                                <div className="flex items-center gap-2">
                                  <span className="font-mono text-xs">
                                    {value.current.toLocaleString()} / {value.max.toLocaleString()}
                                  </span>
                                  {value.passed ? (
                                    <CheckCircle2 className="h-4 w-4 text-green-500" />
                                  ) : (
                                    <XCircle className="h-4 w-4 text-red-500" />
                                  )}
                                </div>
                              </div>
                            ))}
                          </div>
                        </div>
                      )}
                    </div>
                  )}
                </div>

                <div className="space-y-4">
                  <h4 className="font-medium">Validation Results</h4>

                  {validationResult ? (
                    <ScrollArea className="h-[350px]">
                      <div className="space-y-3 pr-4">
                        {validationResult.issues.length === 0 ? (
                          <div className="p-4 bg-green-500/10 border border-green-500/20 rounded-lg">
                            <div className="flex items-center gap-2 text-green-600">
                              <CheckCircle2 className="h-5 w-5" />
                              <span className="font-medium">All checks passed!</span>
                            </div>
                            <p className="text-sm text-muted-foreground mt-1">
                              Your avatar is fully compatible with {avatarPlatforms[selectedPlatform].name}
                            </p>
                          </div>
                        ) : (
                          validationResult.issues.map((issue, i) => (
                            <div
                              key={i}
                              className={`p-3 border rounded-lg ${
                                issue.type === 'error'
                                  ? 'border-red-500/20 bg-red-500/5'
                                  : issue.type === 'warning'
                                  ? 'border-yellow-500/20 bg-yellow-500/5'
                                  : 'border-blue-500/20 bg-blue-500/5'
                              }`}
                            >
                              <div className="flex items-start gap-2">
                                {issue.type === 'error' ? (
                                  <XCircle className="h-4 w-4 text-red-500 mt-0.5" />
                                ) : issue.type === 'warning' ? (
                                  <AlertTriangle className="h-4 w-4 text-yellow-500 mt-0.5" />
                                ) : (
                                  <Info className="h-4 w-4 text-blue-500 mt-0.5" />
                                )}
                                <div className="flex-1">
                                  <p className="text-sm font-medium">{issue.message}</p>
                                  {issue.details && (
                                    <p className="text-xs text-muted-foreground mt-0.5">{issue.details}</p>
                                  )}
                                  {issue.autoFix && (
                                    <Badge variant="outline" className="mt-2 text-xs">
                                      <Zap className="h-3 w-3 mr-1" />
                                      Auto-fixable
                                    </Badge>
                                  )}
                                </div>
                              </div>
                            </div>
                          ))
                        )}

                        {validationResult.optimizationSuggestions.length > 0 && (
                          <>
                            <Separator />
                            <div className="space-y-2">
                              <h5 className="text-sm font-medium flex items-center gap-1.5">
                                <Wand2 className="h-4 w-4" />
                                Optimization Suggestions
                              </h5>
                              {validationResult.optimizationSuggestions.map((suggestion, i) => (
                                <div key={i} className="flex items-start gap-2 text-sm text-muted-foreground">
                                  <ChevronRight className="h-4 w-4 mt-0.5" />
                                  <span>{suggestion}</span>
                                </div>
                              ))}
                            </div>
                          </>
                        )}
                      </div>
                    </ScrollArea>
                  ) : (
                    <div className="flex items-center justify-center h-[350px] border-2 border-dashed rounded-lg">
                      <p className="text-muted-foreground">Validation results will appear here</p>
                    </div>
                  )}
                </div>
              </div>
            </TabsContent>
          </div>
        </Tabs>
      </DialogContent>
    </Dialog>
  );
}
