'use client';

import { useState } from 'react';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import { Label } from '@/components/ui/label';
import { Checkbox } from '@/components/ui/checkbox';
import { Textarea } from '@/components/ui/textarea';
import { Badge } from '@/components/ui/badge';
import { SpatialField } from './spatialQueryReducer';
import {
  Download,
  FileText,
  Globe,
  Database,
  Code,
  Copy,
  CheckCircle
} from 'lucide-react';
import { generateGeoJSON, generateKML, generateCSV, generateSQLExample } from './spatialQueryUtils';
import { toast } from 'sonner';

interface ExportDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  results: SpatialField[];
  queryType: string;
  queryGeometry: any;
  bufferDistance?: number;
}

export function ExportDialog({
  open,
  onOpenChange,
  results,
  queryType,
  queryGeometry,
  bufferDistance
}: ExportDialogProps) {
  const [exportFormat, setExportFormat] = useState<'geojson' | 'kml' | 'csv'>('geojson');
  const [includeGeometry, setIncludeGeometry] = useState(true);
  const [includeAttributes, setIncludeAttributes] = useState(true);
  const [previewContent, setPreviewContent] = useState('');
  const [showPreview, setShowPreview] = useState(false);
  const [copied, setCopied] = useState(false);

  const generateExportData = () => {
    let data = '';

    switch (exportFormat) {
      case 'geojson':
        data = generateGeoJSON(results);
        break;
      case 'kml':
        data = generateKML(results);
        break;
      case 'csv':
        data = generateCSV(results);
        break;
    }

    return data;
  };

  const handlePreview = () => {
    const data = generateExportData();
    setPreviewContent(data.substring(0, 1000) + (data.length > 1000 ? '...' : ''));
    setShowPreview(true);
  };

  const handleDownload = () => {
    const data = generateExportData();
    const blob = new Blob([data], {
      type: getContentType(exportFormat)
    });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = getFileName(exportFormat);
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);

    toast.success(`数据已导出为 ${exportFormat.toUpperCase()} 格式`);
    onOpenChange(false);
  };

  const handleCopyToClipboard = () => {
    const data = generateExportData();
    navigator.clipboard.writeText(data).then(() => {
      setCopied(true);
      toast.success('数据已复制到剪贴板');
      setTimeout(() => setCopied(false), 2000);
    });
  };

  const getContentType = (format: string): string => {
    switch (format) {
      case 'geojson':
        return 'application/json';
      case 'kml':
        return 'application/vnd.google-earth.kml+xml';
      case 'csv':
        return 'text/csv';
      default:
        return 'text/plain';
    }
  };

  const getFileName = (format: string): string => {
    const timestamp = new Date().toISOString().slice(0, 10);
    return `spatial_query_results_${timestamp}.${format}`;
  };

  const formatInfo = {
    geojson: {
      name: 'GeoJSON',
      description: '开放的地理空间数据格式，支持几何和属性信息',
      icon: Globe,
      color: 'text-green-600 dark:text-green-400',
      bgColor: 'bg-green-50 dark:bg-green-950'
    },
    kml: {
      name: 'KML',
      description: 'Google Earth 支持的地理标记语言',
      icon: FileText,
      color: 'text-blue-600 dark:text-blue-400',
      bgColor: 'bg-blue-50 dark:bg-blue-950'
    },
    csv: {
      name: 'CSV',
      description: '表格数据格式，适合在Excel等软件中分析',
      icon: Database,
      color: 'text-purple-600 dark:text-purple-400',
      bgColor: 'bg-purple-50 dark:bg-purple-950'
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>导出查询结果</DialogTitle>
          <DialogDescription>
            将空间查询结果导出为不同格式的数据文件
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-6 py-4">
          {/* 导出统计 */}
          <div className="p-4 bg-muted/50 rounded-lg">
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
              <div>
                <span className="text-muted-foreground">地块数量</span>
                <div className="font-medium">{results.length} 个</div>
              </div>
              <div>
                <span className="text-muted-foreground">总面积</span>
                <div className="font-medium">
                  {results.reduce((sum, field) => sum + field.area, 0).toFixed(1)} 亩
                </div>
              </div>
              <div>
                <span className="text-muted-foreground">查询类型</span>
                <div className="font-medium">{getQueryTypeName(queryType)}</div>
              </div>
              <div>
                <span className="text-muted-foreground">导出时间</span>
                <div className="font-medium">{new Date().toLocaleString()}</div>
              </div>
            </div>
          </div>

          {/* 格式选择 */}
          <div className="space-y-3">
            <Label>导出格式</Label>
            <RadioGroup value={exportFormat} onValueChange={(value: any) => setExportFormat(value)}>
              {Object.entries(formatInfo).map(([key, info]) => {
                const IconComponent = info.icon;
                return (
                  <div key={key} className="flex items-center space-x-2 p-3 border rounded-lg hover:bg-muted/50">
                    <RadioGroupItem value={key} id={key} />
                    <Label htmlFor={key} className="flex-1 cursor-pointer">
                      <div className="flex items-center gap-3">
                        <div className={`p-2 rounded-lg ${info.bgColor}`}>
                          <IconComponent className={`w-4 h-4 ${info.color}`} />
                        </div>
                        <div>
                          <div className="font-medium">{info.name}</div>
                          <div className="text-sm text-muted-foreground">{info.description}</div>
                        </div>
                      </div>
                    </Label>
                  </div>
                );
              })}
            </RadioGroup>
          </div>

          {/* 导出选项 */}
          <div className="space-y-3">
            <Label>导出选项</Label>
            <div className="space-y-2">
              <div className="flex items-center space-x-2">
                <Checkbox
                  id="include-geometry"
                  checked={includeGeometry}
                  onCheckedChange={(checked) => setIncludeGeometry(checked as boolean)}
                />
                <Label htmlFor="include-geometry" className="text-sm">
                  包含几何信息（坐标、边界等）
                </Label>
              </div>
              <div className="flex items-center space-x-2">
                <Checkbox
                  id="include-attributes"
                  checked={includeAttributes}
                  onCheckedChange={(checked) => setIncludeAttributes(checked as boolean)}
                />
                <Label htmlFor="include-attributes" className="text-sm">
                  包含属性信息（面积、土壤类型、负责人等）
                </Label>
              </div>
            </div>
          </div>

          {/* 预览区域 */}
          {showPreview && (
            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <Label>数据预览</Label>
                <Badge variant="outline" className="text-xs">
                  显示前1000字符
                </Badge>
              </div>
              <Textarea
                value={previewContent}
                readOnly
                className="font-mono text-xs bg-muted min-h-[200px]"
                placeholder="预览内容..."
              />
            </div>
          )}

          {/* SQL示例 */}
          <div className="space-y-3">
            <div className="flex items-center gap-2">
              <Code className="w-4 h-4" />
              <Label>PostGIS SQL查询示例</Label>
            </div>
            <Textarea
              value={generateSQLExample(queryType, queryGeometry, bufferDistance)}
              readOnly
              className="font-mono text-sm bg-muted"
              rows={6}
            />
            <Button
              variant="outline"
              size="sm"
              onClick={() => {
                navigator.clipboard.writeText(generateSQLExample(queryType, queryGeometry, bufferDistance));
                toast.success('SQL语句已复制到剪贴板');
              }}
            >
              <Copy className="w-3 h-3 mr-2" />
              复制SQL语句
            </Button>
          </div>
        </div>

        <DialogFooter className="flex gap-2">
          <Button variant="outline" onClick={() => setShowPreview(!showPreview)}>
            {showPreview ? '隐藏预览' : '显示预览'}
          </Button>
          <Button
            variant="outline"
            onClick={handleCopyToClipboard}
            disabled={copied}
          >
            {copied ? (
              <>
                <CheckCircle className="w-4 h-4 mr-2" />
                已复制
              </>
            ) : (
              <>
                <Copy className="w-4 h-4 mr-2" />
                复制到剪贴板
              </>
            )}
          </Button>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            取消
          </Button>
          <Button onClick={handleDownload} className="bg-green-600 hover:bg-green-700">
            <Download className="w-4 h-4 mr-2" />
            下载 {formatInfo[exportFormat].name} 文件
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

// 获取查询类型名称
function getQueryTypeName(type: string): string {
  const names: Record<string, string> = {
    'point-in-polygon': '点在多边形内查询',
    'polygon-intersect': '多边形相交查询',
    'polygon-adjacent': '多边形相邻查询',
    'buffer': '缓冲区查询'
  };
  return names[type] || type;
}