'use client'

import { useRouter, useSearchParams } from 'next/navigation'
import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { FileDown, Calendar as CalendarIcon, Loader2, FileSpreadsheet } from 'lucide-react'
import { jsPDF } from 'jspdf'
import autoTable from 'jspdf-autotable'
import * as XLSX from 'xlsx'

interface DashboardFilterProps {
  chartData: any[]
  title: string
  totalRevenue: number
  totalOrders: number
  siteName: string
  rawExportData?: any[]
  role?: string
}

export function DashboardFilter({ 
  chartData, 
  title, 
  totalRevenue, 
  totalOrders, 
  siteName, 
  rawExportData = [],
  role
}: DashboardFilterProps) {
  const router = useRouter()
  const searchParams = useSearchParams()
  const [isExporting, setIsExporting] = useState(false)
  const [isExportingExcel, setIsExportingExcel] = useState(false)

  const isGA = role === 'SUPER_ADMIN_GA'

  // Current selections
  const currentRange = searchParams.get('range') || 'last7days'
  const currentMonth = searchParams.get('month') || (new Date().getMonth() + 1).toString()
  const currentYear = searchParams.get('year') || new Date().getFullYear().toString()

  const months = [
    { value: '1', label: 'January' }, { value: '2', label: 'February' },
    { value: '3', label: 'March' }, { value: '4', label: 'April' },
    { value: '5', label: 'May' }, { value: '6', label: 'June' },
    { value: '7', label: 'July' }, { value: '8', label: 'August' },
    { value: '9', label: 'September' }, { value: '10', label: 'October' },
    { value: '11', label: 'November' }, { value: '12', label: 'December' }
  ]

  const years = ['2024', '2025', '2026', '2027']

  const handleRangeChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const val = e.target.value
    if (val === 'custom') {
      router.push(`?range=custom&month=${currentMonth}&year=${currentYear}`)
    } else {
      router.push(`?range=${val}`)
    }
  }

  const handleMonthChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    router.push(`?range=custom&month=${e.target.value}&year=${currentYear}`)
  }

  const handleYearChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    router.push(`?range=custom&month=${currentMonth}&year=${e.target.value}`)
  }

  const exportPDF = () => {
    setIsExporting(true)
    try {
      const doc = new jsPDF()

      // Header
      doc.setFontSize(20)
      doc.setTextColor(79, 70, 229) // Primary indigo
      doc.text(`${siteName} - Transaction Report`, 14, 22)
      
      doc.setFontSize(11)
      doc.setTextColor(100, 100, 100)
      doc.text(`Report Period: ${title}`, 14, 30)
      doc.text(`Generated on: ${new Date().toLocaleString('id-ID')}`, 14, 36)

      // Summary
      doc.setFontSize(12)
      doc.setTextColor(0, 0, 0)
      const formattedRev = new Intl.NumberFormat('id-ID', { style: 'currency', currency: 'IDR', maximumFractionDigits: 0 }).format(totalRevenue)
      doc.text(`Total Revenue: ${formattedRev}`, 14, 46)
      doc.text(`Total Orders: ${totalOrders}`, 14, 52)

      // Table Data
      const tableData = rawExportData.map(row => [
        new Date(row.date).toLocaleDateString('id-ID'),
        row.poNumber || '-',
        row.department,
        row.productName,
        row.quantity.toString(),
        new Intl.NumberFormat('id-ID', { style: 'currency', currency: 'IDR', maximumFractionDigits: 0 }).format(row.nominal)
      ])

      autoTable(doc, {
        startY: 60,
        head: [['Date', 'PO Number', 'Department', 'Product', 'Qty', 'Nominal (IDR)']],
        body: tableData,
        theme: 'striped',
        headStyles: { fillColor: [79, 70, 229] }, // matches our primary color
        styles: { font: 'helvetica', fontSize: 10 },
      })

      const fileName = siteName.toLowerCase().replace(/\s+/g, '_')
      doc.save(`${fileName}_transaction_report_${new Date().getTime()}.pdf`)
    } catch (error) {
      console.error("PDF Export failed", error)
    } finally {
      setIsExporting(false)
    }
  }

  const exportExcel = () => {
    setIsExportingExcel(true)
    try {
      const exportData = rawExportData.map(item => ({
        'Tanggal Pembelian': new Date(item.date).toLocaleDateString('id-ID'),
        'PO Number': item.poNumber || '-',
        'Departement Order': item.department,
        'Product': item.productName,
        'Qty': item.quantity,
        'Nominal': item.nominal
      }))

      const ws = XLSX.utils.json_to_sheet(exportData)
      const wb = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(wb, ws, "Transactions")
      const fileName = siteName.toLowerCase().replace(/\s+/g, '_')
      XLSX.writeFile(wb, `${fileName}_transactions_export_${new Date().getTime()}.xlsx`)
    } catch (error) {
      console.error("Excel Export failed", error)
    } finally {
      setIsExportingExcel(false)
    }
  }

  return (
    <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-4 bg-white dark:bg-gray-900 p-4 rounded-xl border border-border shadow-sm">
      <div className="flex flex-wrap items-center gap-3">
        <div className="flex items-center text-sm font-medium text-muted-foreground mr-2">
          <CalendarIcon className="w-4 h-4 mr-2" />
          Filter:
        </div>
        
        <select 
          value={currentRange} 
          onChange={handleRangeChange}
          className="h-9 rounded-md border border-input bg-background px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary"
        >
          <option value="last7days">Last 7 Days</option>
          <option value="thisMonth">This Month</option>
          <option value="thisYear">This Year</option>
          <option value="custom">Specific Month</option>
        </select>

        {currentRange === 'custom' && (
          <div className="flex items-center gap-2 animate-in fade-in slide-in-from-left-2 duration-300">
            <select 
              value={currentMonth} 
              onChange={handleMonthChange}
              className="h-9 rounded-md border border-input bg-background px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary"
            >
              {months.map(m => <option key={m.value} value={m.value}>{m.label}</option>)}
            </select>
            
            <select 
              value={currentYear} 
              onChange={handleYearChange}
              className="h-9 rounded-md border border-input bg-background px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary"
            >
              {years.map(y => <option key={y} value={y}>{y}</option>)}
            </select>
          </div>
        )}
      </div>

      <div className="flex gap-2 w-full sm:w-auto">
        {isGA && (
          <Button 
            onClick={exportExcel} 
            disabled={isExportingExcel || chartData.length === 0} 
            className="w-full sm:w-auto bg-emerald-600 hover:bg-emerald-700 text-white gap-2 transition-all shadow-md shadow-emerald-600/10 rounded-xl"
          >
            {isExportingExcel ? <Loader2 className="w-4 h-4 animate-spin" /> : <FileSpreadsheet className="w-4 h-4" />}
            Export Excel
          </Button>
        )}
        <Button 
          onClick={exportPDF} 
          disabled={isExporting || chartData.length === 0} 
          variant="outline" 
          className="w-full sm:w-auto border-primary/20 text-primary hover:bg-primary hover:text-white transition-all rounded-xl"
        >
          {isExporting ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <FileDown className="w-4 h-4 mr-2" />}
          Export PDF
        </Button>
      </div>
    </div>
  )
}

