import { useState } from 'react';
import { Sparkles, Wand2, FileText } from 'lucide-react';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { Switch } from '@/components/ui/switch';
import { Label } from '@/components/ui/label';
import { Card, CardContent } from '@/components/ui/card';
import { ApiDocument } from '@/service/types';
import { useDocumentProcess } from '@/hooks/useDocuments';
import { useTranslate } from '@/utils/i18n';

interface PreviewPanelProps {
  document: ApiDocument | null;
  onImport?: (docId: number) => void;
}

export default function PreviewPanel({ document, onImport }: PreviewPanelProps) {
  const t = useTranslate();
  const [aiOptions, setAiOptions] = useState({
    enhance_with_ai: true,
    generate_summary: true,
    extract_tags: true,
  });

  const processMutation = useDocumentProcess();

  const handleProcess = async () => {
    if (!document) return;
    await processMutation.mutateAsync({
      docId: document.id,
      options: aiOptions,
    });
  };

  if (!document) {
    return (
      <div className="h-full flex flex-col items-center justify-center text-center p-8">
        <FileText className="w-16 h-16 text-muted-foreground/30 mb-4" />
        <h3 className="text-lg font-medium mb-2">{t('documents.preview.select_title')}</h3>
        <p className="text-sm text-muted-foreground">
          {t('documents.preview.select_description')}
        </p>
      </div>
    );
  }

  const isProcessing = document.status === 'PROCESSING';
  const isProcessed = document.status === 'COMPLETED';

  return (
    <div className="h-full flex flex-col gap-4 p-4 overflow-y-auto">
      {/* Document header */}
      <div className="space-y-2">
        <h2 className="text-xl font-semibold break-words">
          {document.title || document.original_filename}
        </h2>
        <div className="flex items-center gap-2 text-sm text-muted-foreground">
          <span>{(document.file_size / 1024).toFixed(1)} KB</span>
          {document.pages && <span>• {document.pages} pages</span>}
          <span>• {document.mime_type}</span>
        </div>
        {document.tags && document.tags.length > 0 && (
          <div className="flex flex-wrap gap-1.5">
            {document.tags.map((tag) => (
              <span
                key={tag}
                className="px-2 py-0.5 text-xs bg-secondary rounded-full"
              >
                #{tag}
              </span>
            ))}
          </div>
        )}
      </div>

      {/* Summary section */}
      {document.summary && (
        <Card>
          <CardContent className="pt-4">
            <div className="flex items-center gap-2 mb-2">
              <Sparkles className="w-4 h-4 text-primary" />
              <h4 className="font-medium text-sm">{t('documents.preview.summary')}</h4>
            </div>
            <p className="text-sm text-muted-foreground">{document.summary}</p>
          </CardContent>
        </Card>
      )}

      {/* Content preview */}
      <div className="flex-1 min-h-0">
        <h4 className="font-medium text-sm mb-2">{t('documents.preview.content')}</h4>
        <div className="h-full min-h-[300px] p-4 border rounded-lg bg-muted/20 overflow-y-auto">
          {isProcessing ? (
            <div className="flex items-center justify-center h-full">
              <div className="text-center">
                <div className="animate-spin rounded-full h-10 w-10 border-2 border-primary border-t-transparent mx-auto mb-3" />
                <p className="text-sm text-muted-foreground">
                  {t('documents.status.processing')}...
                </p>
              </div>
            </div>
          ) : document.content ? (
            <pre className="text-sm whitespace-pre-wrap font-mono">
              {document.content.slice(0, 10000)}
              {document.content.length > 10000 && '\n... (truncated)'}
            </pre>
          ) : (
            <div className="flex items-center justify-center h-full text-muted-foreground">
              <p>{t('documents.preview.no_content')}</p>
            </div>
          )}
        </div>
      </div>

      {/* AI Enhancement controls */}
      <Card>
        <CardContent className="pt-4 space-y-4">
          <div className="flex items-center gap-2">
            <Wand2 className="w-4 h-4 text-primary" />
            <h4 className="font-medium text-sm">{t('documents.ai_enhance.title')}</h4>
          </div>

          <div className="space-y-3">
            <div className="flex items-center justify-between">
              <Label htmlFor="extract-tags">{t('documents.ai_enhance.extract_tags')}</Label>
              <Switch
                id="extract-tags"
                checked={aiOptions.extract_tags}
                onCheckedChange={(checked) =>
                  setAiOptions({ ...aiOptions, extract_tags: checked })
                }
                disabled={isProcessing}
              />
            </div>

            <div className="flex items-center justify-between">
              <Label htmlFor="generate-summary">{t('documents.ai_enhance.generate_summary')}</Label>
              <Switch
                id="generate-summary"
                checked={aiOptions.generate_summary}
                onCheckedChange={(checked) =>
                  setAiOptions({ ...aiOptions, generate_summary: checked })
                }
                disabled={isProcessing}
              />
            </div>

            <div className="flex items-center justify-between">
              <Label htmlFor="full-enhance">{t('documents.ai_enhance.full_enhance')}</Label>
              <Switch
                id="full-enhance"
                checked={aiOptions.enhance_with_ai}
                onCheckedChange={(checked) =>
                  setAiOptions({ ...aiOptions, enhance_with_ai: checked })
                }
                disabled={isProcessing}
              />
            </div>
          </div>

          <div className="flex gap-2 pt-2">
            <Button
              onClick={handleProcess}
              disabled={isProcessing || processMutation.isPending}
              className="flex-1"
            >
              {isProcessing ? (
                <>
                  <div className="animate-spin rounded-full h-4 w-4 border-2 border-current border-t-transparent mr-2" />
                  {t('documents.ai_enhance.processing')}
                </>
              ) : (
                <>
                  <Sparkles className="w-4 h-4 mr-2" />
                  {t('documents.ai_enhance.enhance')}
                </>
              )}
            </Button>

            {isProcessed && onImport && (
              <Button
                variant="outline"
                onClick={() => onImport(document.id)}
                disabled={importMutation.isPending}
              >
                <FileText className="w-4 h-4 mr-2" />
                {t('documents.import_to_memo')}
              </Button>
            )}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
