import React, { useState, useRef } from 'react'
import { 
  Download, 
  Share2, 
  FileText, 
  Image, 
  Table, 
  Mail,
  Link,
  Copy,
  Check,
  Settings,
  Calendar,
  Filter,
  BarChart3,
  MapPin,
  TrendingUp,
  Code
} from 'lucide-react'
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'
import { CSVLink } from 'react-csv'
import { saveAs } from 'file-saver'

const ExportSharing = ({ 
  data = [],
  chartRefs = {},
  title = 'Export & Share',
  onExport,
  onShare
}) => {
  const [exportFormat, setExportFormat] = useState('pdf')
  const [exportType, setExportType] = useState('chart')
  const [includeData, setIncludeData] = useState(true)
  const [includeMetadata, setIncludeMetadata] = useState(true)
  const [isExporting, setIsExporting] = useState(false)
  const [isSharing, setIsSharing] = useState(false)
  const [shareUrl, setShareUrl] = useState('')
  const [copied, setCopied] = useState(false)
  const [showSettings, setShowSettings] = useState(false)

  const exportFormats = [
    { key: 'pdf', label: 'PDF Report', icon: FileText, description: 'High-quality PDF with charts and data' },
    { key: 'png', label: 'PNG Image', icon: Image, description: 'Chart as high-resolution image' },
    { key: 'csv', label: 'CSV Data', icon: Table, description: 'Raw data in spreadsheet format' },
    { key: 'json', label: 'JSON Data', icon: FileText, description: 'Structured data for developers' }
  ]

  const exportTypes = [
    { key: 'chart', label: 'Charts Only', icon: BarChart3 },
    { key: 'data', label: 'Data Only', icon: Table },
    { key: 'full', label: 'Full Report', icon: FileText },
    { key: 'map', label: 'Map View', icon: MapPin }
  ]

  const shareOptions = [
    { key: 'link', label: 'Generate Link', icon: Link, description: 'Create shareable link' },
    { key: 'email', label: 'Email Report', icon: Mail, description: 'Send via email' },
    { key: 'embed', label: 'Embed Code', icon: Code, description: 'Get embed code' }
  ]

  const handleExport = async () => {
    setIsExporting(true)
    try {
      const timestamp = new Date().toISOString().split('T')[0]
      const filename = `dubai-analytics-${exportType}-${timestamp}`

      switch (exportFormat) {
        case 'pdf':
          await exportToPDF(filename)
          break
        case 'png':
          await exportToPNG(filename)
          break
        case 'csv':
          exportToCSV(filename)
          break
        case 'json':
          exportToJSON(filename)
          break
        default:
          throw new Error('Unsupported export format')
      }

      if (onExport) {
        onExport({ format: exportFormat, type: exportType, filename })
      }
    } catch (error) {
      console.error('Export failed:', error)
      alert('Export failed. Please try again.')
    } finally {
      setIsExporting(false)
    }
  }

  const exportToPDF = async (filename) => {
    const pdf = new jsPDF('l', 'mm', 'a4')
    const pageWidth = pdf.internal.pageSize.getWidth()
    const pageHeight = pdf.internal.pageSize.getHeight()
    
    // Add title
    pdf.setFontSize(20)
    pdf.text('Dubai Real Estate Analytics Report', 20, 30)
    
    // Add metadata
    if (includeMetadata) {
      pdf.setFontSize(12)
      pdf.text(`Generated on: ${new Date().toLocaleDateString()}`, 20, 45)
      pdf.text(`Data points: ${data.length}`, 20, 55)
    }

    let yPosition = 70

    // Export charts
    for (const [chartName, chartRef] of Object.entries(chartRefs)) {
      if (chartRef && chartRef.current) {
        try {
          const canvas = await html2canvas(chartRef.current, {
            scale: 2,
            useCORS: true,
            backgroundColor: '#ffffff'
          })
          
          const imgData = canvas.toDataURL('image/png')
          const imgWidth = pageWidth - 40
          const imgHeight = (canvas.height * imgWidth) / canvas.width
          
          // Check if we need a new page
          if (yPosition + imgHeight > pageHeight - 20) {
            pdf.addPage()
            yPosition = 20
          }
          
          pdf.addImage(imgData, 'PNG', 20, yPosition, imgWidth, imgHeight)
          yPosition += imgHeight + 20
        } catch (error) {
          console.error(`Failed to export chart ${chartName}:`, error)
        }
      }
    }

    // Add data table if requested
    if (includeData && data.length > 0) {
      pdf.addPage()
      pdf.setFontSize(16)
      pdf.text('Data Summary', 20, 30)
      
      yPosition = 50
      const headers = Object.keys(data[0])
      const colWidth = (pageWidth - 40) / headers.length
      
      // Table headers
      pdf.setFontSize(10)
      headers.forEach((header, index) => {
        pdf.text(header, 20 + (index * colWidth), yPosition)
      })
      
      yPosition += 10
      
      // Table data (first 20 rows)
      data.slice(0, 20).forEach((row, rowIndex) => {
        if (yPosition > pageHeight - 20) {
          pdf.addPage()
          yPosition = 20
        }
        
        headers.forEach((header, colIndex) => {
          const value = String(row[header] || '').substring(0, 20)
          pdf.text(value, 20 + (colIndex * colWidth), yPosition)
        })
        yPosition += 10
      })
    }

    pdf.save(`${filename}.pdf`)
  }

  const exportToPNG = async (filename) => {
    const chartRef = Object.values(chartRefs)[0] // Export first chart
    if (!chartRef || !chartRef.current) {
      throw new Error('No chart to export')
    }

    const canvas = await html2canvas(chartRef.current, {
      scale: 2,
      useCORS: true,
      backgroundColor: '#ffffff'
    })
    
    canvas.toBlob((blob) => {
      saveAs(blob, `${filename}.png`)
    })
  }

  const exportToCSV = (filename) => {
    // This will be handled by the CSVLink component
  }

  const exportToJSON = (filename) => {
    const jsonData = {
      metadata: {
        generated: new Date().toISOString(),
        dataPoints: data.length,
        version: '1.0'
      },
      data: data
    }
    
    const blob = new Blob([JSON.stringify(jsonData, null, 2)], { type: 'application/json' })
    saveAs(blob, `${filename}.json`)
  }

  const handleShare = async (type) => {
    setIsSharing(true)
    try {
      switch (type) {
        case 'link':
          const url = await generateShareableLink()
          setShareUrl(url)
          break
        case 'email':
          await shareViaEmail()
          break
        case 'embed':
          await generateEmbedCode()
          break
        default:
          throw new Error('Unsupported share type')
      }

      if (onShare) {
        onShare({ type, data })
      }
    } catch (error) {
      console.error('Share failed:', error)
      alert('Share failed. Please try again.')
    } finally {
      setIsSharing(false)
    }
  }

  const generateShareableLink = async () => {
    // In a real app, this would generate a server-side shareable link
    const baseUrl = window.location.origin
    const shareId = Math.random().toString(36).substring(7)
    const url = `${baseUrl}/share/${shareId}`
    
    // Simulate API call
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    return url
  }

  const shareViaEmail = async () => {
    const subject = 'Dubai Real Estate Analytics Report'
    const body = `Please find the attached analytics report generated on ${new Date().toLocaleDateString()}.`
    const mailtoUrl = `mailto:?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`
    
    window.open(mailtoUrl)
  }

  const generateEmbedCode = async () => {
    const embedCode = `<iframe src="${window.location.href}" width="800" height="600" frameborder="0"></iframe>`
    
    // Copy to clipboard
    await navigator.clipboard.writeText(embedCode)
    setCopied(true)
    setTimeout(() => setCopied(false), 2000)
  }

  const copyToClipboard = async (text) => {
    await navigator.clipboard.writeText(text)
    setCopied(true)
    setTimeout(() => setCopied(false), 2000)
  }

  const csvData = data.map(item => ({
    ...item,
    date: new Date(item.date).toLocaleDateString()
  }))

  return (
    <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-xl border border-gray-200 dark:border-gray-700">
      {/* Header */}
      <div className="p-6 border-b border-gray-200 dark:border-gray-700">
        <div className="flex items-center justify-between">
          <div>
            <h3 className="text-lg font-bold text-gray-900 dark:text-white mb-1">
              {title}
            </h3>
            <p className="text-sm text-gray-600 dark:text-gray-400">
              Export charts and data in various formats
            </p>
          </div>
          
          <button
            onClick={() => setShowSettings(!showSettings)}
            className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
            title="Export Settings"
          >
            <Settings className="h-4 w-4" />
          </button>
        </div>
      </div>

      <div className="p-6 space-y-6">
        {/* Export Section */}
        <div>
          <h4 className="text-sm font-semibold text-gray-900 dark:text-white mb-4 flex items-center">
            <Download className="h-4 w-4 mr-2" />
            Export Options
          </h4>
          
          {/* Export Format */}
          <div className="mb-4">
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              Export Format
            </label>
            <div className="grid grid-cols-2 gap-3">
              {exportFormats.map(format => (
                <button
                  key={format.key}
                  onClick={() => setExportFormat(format.key)}
                  className={`p-3 rounded-lg border-2 transition-all ${
                    exportFormat === format.key
                      ? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20'
                      : 'border-gray-200 dark:border-gray-600 hover:border-gray-300 dark:hover:border-gray-500'
                  }`}
                >
                  <div className="flex items-center space-x-2">
                    <format.icon className="h-4 w-4" />
                    <span className="text-sm font-medium">{format.label}</span>
                  </div>
                  <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                    {format.description}
                  </p>
                </button>
              ))}
            </div>
          </div>

          {/* Export Type */}
          <div className="mb-4">
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              Content Type
            </label>
            <div className="flex space-x-2">
              {exportTypes.map(type => (
                <button
                  key={type.key}
                  onClick={() => setExportType(type.key)}
                  className={`flex items-center space-x-2 px-3 py-2 rounded-lg border transition-all ${
                    exportType === type.key
                      ? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400'
                      : 'border-gray-200 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:border-gray-300 dark:hover:border-gray-500'
                  }`}
                >
                  <type.icon className="h-4 w-4" />
                  <span className="text-sm font-medium">{type.label}</span>
                </button>
              ))}
            </div>
          </div>

          {/* Export Settings */}
          {showSettings && (
            <div className="mb-4 p-4 bg-gray-50 dark:bg-gray-700 rounded-lg">
              <h5 className="text-sm font-semibold text-gray-900 dark:text-white mb-3">Export Settings</h5>
              <div className="space-y-2">
                <label className="flex items-center space-x-2">
                  <input
                    type="checkbox"
                    checked={includeData}
                    onChange={(e) => setIncludeData(e.target.checked)}
                    className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                  />
                  <span className="text-sm text-gray-700 dark:text-gray-300">Include raw data</span>
                </label>
                <label className="flex items-center space-x-2">
                  <input
                    type="checkbox"
                    checked={includeMetadata}
                    onChange={(e) => setIncludeMetadata(e.target.checked)}
                    className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                  />
                  <span className="text-sm text-gray-700 dark:text-gray-300">Include metadata</span>
                </label>
              </div>
            </div>
          )}

          {/* Export Button */}
          <button
            onClick={handleExport}
            disabled={isExporting}
            className="w-full bg-blue-600 hover:bg-blue-700 disabled:bg-blue-400 text-white font-medium py-2 px-4 rounded-lg transition-colors flex items-center justify-center space-x-2"
          >
            {isExporting ? (
              <>
                <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                <span>Exporting...</span>
              </>
            ) : (
              <>
                <Download className="h-4 w-4" />
                <span>Export {exportFormats.find(f => f.key === exportFormat)?.label}</span>
              </>
            )}
          </button>

          {/* CSV Download Link */}
          {exportFormat === 'csv' && (
            <div className="mt-2">
              <CSVLink
                data={csvData}
                filename={`dubai-analytics-${new Date().toISOString().split('T')[0]}.csv`}
                className="block w-full bg-green-600 hover:bg-green-700 text-white font-medium py-2 px-4 rounded-lg transition-colors text-center"
              >
                <Table className="h-4 w-4 inline mr-2" />
                Download CSV
              </CSVLink>
            </div>
          )}
        </div>

        {/* Share Section */}
        <div>
          <h4 className="text-sm font-semibold text-gray-900 dark:text-white mb-4 flex items-center">
            <Share2 className="h-4 w-4 mr-2" />
            Share Options
          </h4>
          
          <div className="grid grid-cols-1 gap-3">
            {shareOptions.map(option => (
              <button
                key={option.key}
                onClick={() => handleShare(option.key)}
                disabled={isSharing}
                className="p-3 rounded-lg border border-gray-200 dark:border-gray-600 hover:border-gray-300 dark:hover:border-gray-500 transition-all text-left disabled:opacity-50"
              >
                <div className="flex items-center justify-between">
                  <div className="flex items-center space-x-2">
                    <option.icon className="h-4 w-4" />
                    <span className="text-sm font-medium">{option.label}</span>
                  </div>
                  {isSharing && (
                    <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600"></div>
                  )}
                </div>
                <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                  {option.description}
                </p>
              </button>
            ))}
          </div>

          {/* Share URL */}
          {shareUrl && (
            <div className="mt-4 p-3 bg-gray-50 dark:bg-gray-700 rounded-lg">
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                Shareable Link
              </label>
              <div className="flex items-center space-x-2">
                <input
                  type="text"
                  value={shareUrl}
                  readOnly
                  className="flex-1 text-sm border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2 bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                />
                <button
                  onClick={() => copyToClipboard(shareUrl)}
                  className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
                  title="Copy to clipboard"
                >
                  {copied ? <Check className="h-4 w-4 text-green-500" /> : <Copy className="h-4 w-4" />}
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}

export default ExportSharing
