import React, { useState } from 'react';
import { useCaptureStore } from '../store/captureStore';
import { downloadImage, estimateDataUrlSizeKB } from '../lib/canvas-capture';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from './ui/card';
import { Button } from './ui/button';
import { Slider } from './ui/slider';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Badge } from './ui/badge';
import { Separator } from './ui/separator';
import { Camera, Download, Trash2, ImageIcon, ChevronRight } from 'lucide-react';

const SceneCapturePanel: React.FC = () => {
  const {
    canvas,
    capturedImage,
    capturedAt,
    targetWidth,
    jpegQuality,
    format,
    setTargetWidth,
    setFormat,
    setJpegQuality,
    capture,
    clearCaptured,
  } = useCaptureStore();

  const [isCapturing, setIsCapturing] = useState(false);

  const handleCapture = async () => {
    setIsCapturing(true);
    try {
      await capture();
    } finally {
      setIsCapturing(false);
    }
  };

  const handleDownload = () => {
    if (capturedImage) {
      const ext = format === 'jpeg' ? 'jpg' : format;
      downloadImage(capturedImage, `cena_vento_${Date.now()}.${ext}`);
    }
  };

  const sizeKB = capturedImage ? estimateDataUrlSizeKB(capturedImage) : 0;

  return (
    <Card className="shadow-sm border-border">
      <CardHeader className="pb-3">
        <CardTitle className="text-lg flex items-center gap-2">
          <Camera className="w-5 h-5 text-primary" />
          Captura 3D (M9.3)
        </CardTitle>
        <CardDescription>
          Screenshot da cena 3D para incluir no PDF ou exportar isoladamente.
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        <div className="space-y-2">
          <label className="text-sm font-medium text-foreground">Formato de Saída</label>
          <Select value={format} onValueChange={(v) => setFormat(v as 'png' | 'jpeg')}>
            <SelectTrigger className="w-full">
              <SelectValue placeholder="Formato" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="png">PNG (sem perda)</SelectItem>
              <SelectItem value="jpeg">JPEG (compactado)</SelectItem>
            </SelectContent>
          </Select>
        </div>

        <div className="space-y-3">
          <div className="flex justify-between items-center">
            <label className="text-sm font-medium text-foreground">Largura máxima (px)</label>
            <span className="text-sm text-muted-foreground font-mono">{targetWidth} px</span>
          </div>
          <Slider
            min={400}
            max={3200}
            step={100}
            value={[targetWidth]}
            onValueChange={(vals) => setTargetWidth(vals[0])}
            className="py-1 cursor-pointer"
          />
          <p className="text-xs text-muted-foreground">
            0 mantém resolução original do canvas. 1600 px é ideal para PDF A4.
          </p>
        </div>

        {format === 'jpeg' && (
          <div className="space-y-3">
            <div className="flex justify-between items-center">
              <label className="text-sm font-medium text-foreground">Qualidade JPEG</label>
              <span className="text-sm text-muted-foreground font-mono">
                {Math.round(jpegQuality * 100)}%
              </span>
            </div>
            <Slider
              min={0.5}
              max={1}
              step={0.02}
              value={[jpegQuality]}
              onValueChange={(vals) => setJpegQuality(vals[0])}
              className="py-1 cursor-pointer"
            />
          </div>
        )}

        <Separator />

        <Button
          onClick={handleCapture}
          disabled={!canvas || isCapturing}
          className="w-full"
          variant="default"
        >
          <Camera className="w-4 h-4 mr-2" />
          {isCapturing ? 'Capturando...' : canvas ? 'Capturar cena atual' : 'Aguardando canvas...'}
        </Button>

        {capturedImage && (
          <>
            <div className="rounded-md border bg-muted/20 p-2 space-y-2">
              <div className="flex items-center justify-between text-xs">
                <div className="flex items-center gap-2">
                  <ImageIcon className="w-4 h-4 text-muted-foreground" />
                  <span className="font-medium">Preview</span>
                </div>
                <Badge variant="outline" className="font-mono text-[10px]">
                  {format.toUpperCase()} · {sizeKB} KB
                </Badge>
              </div>
              <img
                src={capturedImage}
                alt="Captura 3D"
                className="w-full h-auto rounded border bg-background"
                style={{ maxHeight: '180px', objectFit: 'contain' }}
              />
              {capturedAt && (
                <p className="text-[10px] text-muted-foreground text-center">
                  Capturado em {new Date(capturedAt).toLocaleTimeString('pt-BR')}
                </p>
              )}
            </div>

            <div className="flex gap-2">
              <Button
                onClick={handleDownload}
                variant="outline"
                size="sm"
                className="flex-1 text-blue-600 border-blue-200 hover:bg-blue-50"
              >
                <Download className="w-4 h-4 mr-2" />
                Baixar
              </Button>
              <Button
                onClick={clearCaptured}
                variant="outline"
                size="sm"
                className="text-red-600 border-red-200 hover:bg-red-50"
              >
                <Trash2 className="w-4 h-4" />
              </Button>
            </div>

            <p className="text-[11px] text-muted-foreground leading-relaxed">
              <ChevronRight className="w-3 h-3 inline -mt-0.5" /> A imagem será incluída automaticamente
              no PDF quando você exportar após capturar.
            </p>
          </>
        )}
      </CardContent>
    </Card>
  );
};

export default SceneCapturePanel;