import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { 
  FileText, 
  Download, 
  Plus, 
  Clock, 
  CheckCircle, 
  XCircle,
  Filter,
  Calendar
} from 'lucide-react'
import { reportsAPI } from '../services/api'
import toast from 'react-hot-toast'

const Reports = () => {
  const [showGenerateModal, setShowGenerateModal] = useState(false)
  const [reportType, setReportType] = useState('transaction_summary')
  const [reportData, setReportData] = useState({
    area: '',
    property_type: '',
    start_date: '',
    end_date: '',
    format: 'pdf'
  })

  const { data: reports, isLoading, refetch } = useQuery({
    queryKey: ['reports'],
    queryFn: reportsAPI.getReports,
    placeholderData: [], // Provide empty array as placeholder
  })

  // Mock data for demonstration when backend is not available
  const mockReports = [
    {
      id: '1',
      title: 'Monthly Transaction Summary',
      report_type: 'transaction_summary',
      format: 'pdf',
      status: 'completed',
      created_at: '2024-01-15T10:30:00Z',
      file_size: 2048
    },
    {
      id: '2',
      title: 'Dubai Marina Analysis',
      report_type: 'area_analysis',
      format: 'excel',
      status: 'processing',
      created_at: '2024-01-14T15:20:00Z',
      file_size: null
    },
    {
      id: '3',
      title: 'Q1 2024 Forecast',
      report_type: 'forecast',
      format: 'pdf',
      status: 'failed',
      created_at: '2024-01-13T09:15:00Z',
      file_size: null
    }
  ]

  const displayReports = reports && reports.length > 0 ? reports : mockReports

  const handleGenerateReport = async () => {
    try {
      let response
      
      switch (reportType) {
        case 'transaction_summary':
          response = await reportsAPI.generateTransactionSummary(reportData)
          break
        case 'area_analysis':
          response = await reportsAPI.generateAreaAnalysis(reportData)
          break
        case 'forecast':
          response = await reportsAPI.generateForecast(reportData)
          break
        default:
          throw new Error('Invalid report type')
      }

      if (response.data) {
        toast.success('Report generation started')
        setShowGenerateModal(false)
        refetch()
      }
    } catch (error) {
      toast.error('Failed to generate report')
    }
  }

  const handleDownloadReport = async (reportId) => {
    try {
      const response = await reportsAPI.downloadReport(reportId)
      
      // Create blob and download
      const blob = new Blob([response.data])
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `report-${reportId}.${reportData.format}`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
      
      toast.success('Report downloaded successfully')
    } catch (error) {
      toast.error('Failed to download report')
    }
  }

  const getStatusIcon = (status) => {
    switch (status) {
      case 'completed':
        return <CheckCircle className="h-5 w-5 text-green-500" />
      case 'failed':
        return <XCircle className="h-5 w-5 text-red-500" />
      case 'processing':
        return <Clock className="h-5 w-5 text-yellow-500 animate-spin" />
      default:
        return <Clock className="h-5 w-5 text-gray-400" />
    }
  }

  const getStatusColor = (status) => {
    switch (status) {
      case 'completed':
        return 'bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400'
      case 'failed':
        return 'bg-red-100 text-red-800 dark:bg-red-900/20 dark:text-red-400'
      case 'processing':
        return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/20 dark:text-yellow-400'
      default:
        return 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-200'
    }
  }

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-primary-600"></div>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-xl font-bold text-gray-900 dark:text-white tracking-tight">
            Reports
          </h1>
          <p className="text-sm text-gray-600 dark:text-gray-400 font-normal">
            Generate and manage analytical reports
          </p>
        </div>
        <button
          onClick={() => setShowGenerateModal(true)}
          className="btn btn-primary btn-md"
        >
          <Plus className="h-4 w-4 mr-2" />
          Generate Report
        </button>
      </div>

      {/* Reports List */}
      <div className="card">
        <div className="overflow-x-auto">
          <table className="table">
            <thead className="table-header">
              <tr className="table-row">
                <th className="table-head">Title</th>
                <th className="table-head">Type</th>
                <th className="table-head">Format</th>
                <th className="table-head">Status</th>
                <th className="table-head">Created</th>
                <th className="table-head">Size</th>
                <th className="table-head">Actions</th>
              </tr>
            </thead>
            <tbody className="table-body">
              {displayReports?.map((report) => (
                <tr key={report.id} className="table-row">
                  <td className="table-cell">
                    <div className="flex items-center space-x-3">
                      <FileText className="h-5 w-5 text-gray-400" />
                      <div>
                        <p className="font-medium text-gray-900 dark:text-white">
                          {report.title}
                        </p>
                        <p className="text-sm text-gray-500 dark:text-gray-400">
                          ID: {report.id}
                        </p>
                      </div>
                    </div>
                  </td>
                  <td className="table-cell">
                    <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-slate-100 text-slate-800 dark:bg-slate-900/20 dark:text-slate-400">
                      {report.report_type.replace('_', ' ')}
                    </span>
                  </td>
                  <td className="table-cell">
                    <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-200">
                      {report.format.toUpperCase()}
                    </span>
                  </td>
                  <td className="table-cell">
                    <div className="flex items-center space-x-2">
                      {getStatusIcon(report.status)}
                      <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${getStatusColor(report.status)}`}>
                        {report.status}
                      </span>
                    </div>
                  </td>
                  <td className="table-cell text-sm text-gray-500 dark:text-gray-400">
                    {new Date(report.created_at).toLocaleDateString()}
                  </td>
                  <td className="table-cell text-sm text-gray-500 dark:text-gray-400">
                    {report.file_size ? `${(report.file_size / 1024).toFixed(1)} KB` : '-'}
                  </td>
                  <td className="table-cell">
                    <div className="flex items-center space-x-2">
                      {report.status === 'completed' && (
                        <button
                          onClick={() => handleDownloadReport(report.id)}
                          className="p-1 text-slate-600 hover:text-slate-800"
                          title="Download Report"
                        >
                          <Download className="h-4 w-4" />
                        </button>
                      )}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Generate Report Modal */}
      {showGenerateModal && (
        <div className="fixed inset-0 z-50 overflow-y-auto">
          <div className="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
            <div className="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" onClick={() => setShowGenerateModal(false)}></div>
            
            <div className="inline-block align-bottom bg-white dark:bg-gray-800 rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
              <div className="bg-white dark:bg-gray-800 px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-4">
                  Generate Report
                </h3>
                
                <div className="space-y-4">
                  <div>
                    <label className="label">Report Type</label>
                    <select
                      value={reportType}
                      onChange={(e) => setReportType(e.target.value)}
                      className="input"
                    >
                      <option value="transaction_summary">Transaction Summary</option>
                      <option value="area_analysis">Area Analysis</option>
                      <option value="forecast">Forecast Report</option>
                    </select>
                  </div>

                  <div>
                    <label className="label">Area</label>
                    <input
                      type="text"
                      placeholder="Enter area (optional)"
                      value={reportData.area}
                      onChange={(e) => setReportData({...reportData, area: e.target.value})}
                      className="input"
                    />
                  </div>

                  <div>
                    <label className="label">Property Type</label>
                    <select
                      value={reportData.property_type}
                      onChange={(e) => setReportData({...reportData, property_type: e.target.value})}
                      className="input"
                    >
                      <option value="">All Types</option>
                      <option value="Unit">Unit</option>
                      <option value="Villa">Villa</option>
                      <option value="Land">Land</option>
                      <option value="Building">Building</option>
                    </select>
                  </div>

                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="label">Start Date</label>
                      <input
                        type="date"
                        value={reportData.start_date}
                        onChange={(e) => setReportData({...reportData, start_date: e.target.value})}
                        className="input"
                      />
                    </div>
                    <div>
                      <label className="label">End Date</label>
                      <input
                        type="date"
                        value={reportData.end_date}
                        onChange={(e) => setReportData({...reportData, end_date: e.target.value})}
                        className="input"
                      />
                    </div>
                  </div>

                  <div>
                    <label className="label">Format</label>
                    <select
                      value={reportData.format}
                      onChange={(e) => setReportData({...reportData, format: e.target.value})}
                      className="input"
                    >
                      <option value="pdf">PDF</option>
                      <option value="excel">Excel</option>
                      <option value="csv">CSV</option>
                    </select>
                  </div>
                </div>
              </div>

              <div className="bg-gray-50 dark:bg-gray-700 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                <button
                  onClick={handleGenerateReport}
                  className="btn btn-primary btn-md mr-3"
                >
                  Generate Report
                </button>
                <button
                  onClick={() => setShowGenerateModal(false)}
                  className="btn btn-secondary btn-md"
                >
                  Cancel
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

export default Reports

