'use client';

import React, { useState } from 'react';
import { Copy, ChevronDown, ChevronUp } from 'lucide-react';
import { Stack } from '@/ui/Stack';
import { Text } from '@/ui/Text';
import { Button } from '@/ui/Button';
import { Icon } from '@/ui/Icon';
import { Card } from '@/ui/Card';

interface ErrorDetailsBlockProps {
  error: Error & { digest?: string };
}

/**
 * ErrorDetailsBlock
 * 
 * Semantic component for technical error details.
 * Follows "Precision Racing Minimal" theme.
 */
export function ErrorDetailsBlock({ error }: ErrorDetailsBlockProps) {
  const [showDetails, setShowDetails] = useState(false);
  const [copied, setCopied] = useState(false);

  const copyError = async () => {
    const details = {
      message: error.message,
      digest: error.digest,
      stack: error.stack,
      url: typeof window !== 'undefined' ? window.location.href : 'unknown',
      timestamp: new Date().toISOString(),
    };
    
    try {
      await navigator.clipboard.writeText(JSON.stringify(details, null, 2));
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch (err) {
      // Silent fail
    }
  };

  return (
    <Stack gap={4} fullWidth pt={4} borderTop borderColor="border-white">
      <Stack 
        as="button"
        onClick={() => setShowDetails(!showDetails)}
        direction="row"
        align="center"
        justify="center"
        gap={2}
        className="transition-all"
      >
        <Text 
          size="xs" 
          color="text-gray-500" 
          className="hover:text-gray-300 flex items-center gap-2"
          uppercase 
          letterSpacing="widest" 
          weight="medium"
        >
          {showDetails ? <Icon icon={ChevronUp} size={3} /> : <Icon icon={ChevronDown} size={3} />}
          {showDetails ? 'Hide Technical Logs' : 'Show Technical Logs'}
        </Text>
      </Stack>

      {showDetails && (
        <Stack gap={3}>
          <Card 
            variant="outline"
            rounded="md" 
            p={4} 
            fullWidth
            maxHeight="48"
            overflow="auto"
            borderColor="border-white"
            className="bg-graphite-black/40"
          >
            <Text font="mono" size="xs" color="text-gray-500" block leading="relaxed">
              {error.stack || 'No stack trace available'}
              {error.digest && `\n\nDigest: ${error.digest}`}
            </Text>
          </Card>
          
          <Stack direction="row" justify="end">
            <Button 
              variant="secondary" 
              size="sm"
              onClick={copyError}
              icon={<Icon icon={Copy} size={3} />}
              height="8"
              fontSize="10px"
            >
              {copied ? 'Copied to Clipboard' : 'Copy Error Details'}
            </Button>
          </Stack>
        </Stack>
      )}
    </Stack>
  );
}
