'use client'

import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import axios from 'axios'
import { BarChart2, Download, Calendar, Search, FileText, TrendingUp, Shield, Users, CreditCard, PiggyBank, Briefcase, DollarSign, Activity } from 'lucide-react'
import { Button, Card, CardContent, Input, Badge, Tabs, PageHeader, EmptyState } from '@/components/ui/components'
import { cn } from '@/lib/utils'

const CATEGORY_ICONS: Record<string, React.ReactNode> = {
  LOANS:       <CreditCard className="w-5 h-5"/>,
  SASRA:       <Shield className="w-5 h-5"/>,
  IFRS9:       <TrendingUp className="w-5 h-5"/>,
  ACCOUNTING:  <BarChart2 className="w-5 h-5"/>,
  MEMBERS:     <Users className="w-5 h-5"/>,
  SAVINGS:     <PiggyBank className="w-5 h-5"/>,
  COLLECTIONS: <Activity className="w-5 h-5"/>,
  PAYROLL:     <Briefcase className="w-5 h-5"/>,
  EXPENSES:    <DollarSign className="w-5 h-5"/>,
  GROUPS:      <Users className="w-5 h-5"/>,
  AML:         <Shield className="w-5 h-5"/>,
  AUDIT:       <FileText className="w-5 h-5"/>,
  ASSETS:      <BarChart2 className="w-5 h-5"/>,
}

const CATEGORY_COLORS: Record<string, string> = {
  LOANS:'blue', SASRA:'purple', IFRS9:'red', ACCOUNTING:'green',
  MEMBERS:'teal', SAVINGS:'blue', COLLECTIONS:'amber', PAYROLL:'green',
  EXPENSES:'orange', GROUPS:'teal', AML:'red', AUDIT:'gray', ASSETS:'brown',
}

export default function ReportsPage() {
  const [search, setSearch] = useState('')
  const [category, setCategory] = useState('ALL')
  const [running, setRunning] = useState<string | null>(null)
  const [dateFrom, setDateFrom] = useState(new Date(new Date().getFullYear(), new Date().getMonth(), 1).toISOString().slice(0,10))
  const [dateTo, setDateTo]     = useState(new Date().toISOString().slice(0,10))

  const { data } = useQuery({
    queryKey: ['saved-reports'],
    queryFn: () => axios.get('/api/reports').then(r => r.data.data),
  })

  const reports = data ?? []
  const categories = ['ALL', ...Array.from(new Set(reports.map((r: any) => r.category)))] as string[]

  const filtered = reports.filter((r: any) => {
    const matchSearch = !search || r.name.toLowerCase().includes(search.toLowerCase())
    const matchCat    = category === 'ALL' || r.category === category
    return matchSearch && matchCat
  })

  const grouped = filtered.reduce((acc: Record<string,any[]>, r: any) => {
    if (!acc[r.category]) acc[r.category] = []
    acc[r.category].push(r)
    return acc
  }, {})

  async function runReport(report: any, format: 'EXCEL' | 'PDF') {
    setRunning(report.id)
    try {
      const res = await axios.post('/api/reports', { reportId: report.id, format, dateFrom, dateTo }, { responseType: 'blob' })
      const url  = window.URL.createObjectURL(new Blob([res.data]))
      const link = document.createElement('a')
      link.href  = url
      link.download = `${report.name.replace(/\s+/g,'-')}-${dateFrom}-${dateTo}.${format === 'EXCEL' ? 'xlsx' : 'pdf'}`
      document.body.appendChild(link)
      link.click()
      link.remove()
      window.URL.revokeObjectURL(url)
    } catch {
      // Generate a mock CSV for demo purposes
      const csvData = `Report: ${report.name}\nDate From: ${dateFrom}\nDate To: ${dateTo}\n\nGenerated at: ${new Date().toLocaleString()}\n\nData would be populated from the database here.`
      const blob = new Blob([csvData], { type: 'text/csv' })
      const url  = URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href  = url
      link.download = `${report.name.replace(/\s+/g,'-')}.csv`
      document.body.appendChild(link)
      link.click()
      link.remove()
    } finally { setRunning(null) }
  }

  return (
    <div className="p-6 space-y-5 max-w-screen-2xl mx-auto">
      <PageHeader title="Reports" description={`${reports.length} reports available`} icon={<BarChart2 className="w-6 h-6"/>}/>

      {/* Date range filter */}
      <div className="bg-card border rounded-xl p-4 flex flex-wrap items-end gap-3">
        <div>
          <label className="block text-xs font-medium text-muted-foreground mb-1">From</label>
          <input type="date" value={dateFrom} onChange={e => setDateFrom(e.target.value)} className="border rounded-lg px-3 py-2 text-sm bg-background focus:outline-none focus:ring-2 focus:ring-primary/20"/>
        </div>
        <div>
          <label className="block text-xs font-medium text-muted-foreground mb-1">To</label>
          <input type="date" value={dateTo} onChange={e => setDateTo(e.target.value)} className="border rounded-lg px-3 py-2 text-sm bg-background focus:outline-none focus:ring-2 focus:ring-primary/20"/>
        </div>
        <div className="flex gap-2 flex-wrap">
          {[
            { l:'This Month',   f: new Date(new Date().getFullYear(), new Date().getMonth(), 1),    t: new Date() },
            { l:'Last Month',   f: new Date(new Date().getFullYear(), new Date().getMonth()-1, 1),  t: new Date(new Date().getFullYear(), new Date().getMonth(), 0) },
            { l:'This Quarter', f: new Date(new Date().getFullYear(), Math.floor(new Date().getMonth()/3)*3, 1), t: new Date() },
            { l:'This Year',    f: new Date(new Date().getFullYear(), 0, 1), t: new Date() },
          ].map(p => (
            <button key={p.l} onClick={() => { setDateFrom(p.f.toISOString().slice(0,10)); setDateTo(p.t.toISOString().slice(0,10)) }}
              className="px-3 py-2 text-xs border rounded-lg hover:bg-accent transition-colors"
            >
              {p.l}
            </button>
          ))}
        </div>
        <div className="flex-1 min-w-[200px] relative">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"/>
          <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search reports..." className="w-full pl-9 pr-4 py-2 border rounded-lg text-sm bg-background focus:outline-none focus:ring-2 focus:ring-primary/20"/>
        </div>
      </div>

      {/* Category tabs */}
      <div className="flex gap-2 flex-wrap">
        {categories.map(cat => (
          <button key={cat} onClick={() => setCategory(cat)}
            className={cn('flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded-lg border transition-colors', category === cat ? 'bg-primary text-primary-foreground border-primary' : 'bg-card hover:bg-accent text-muted-foreground')}
          >
            {cat !== 'ALL' && CATEGORY_ICONS[cat]}{cat}
            <span className={cn('rounded-full px-1.5 text-xs', category === cat ? 'bg-white/20' : 'bg-muted')}>
              {cat === 'ALL' ? reports.length : reports.filter((r: any) => r.category === cat).length}
            </span>
          </button>
        ))}
      </div>

      {/* Report grid by category */}
      {Object.keys(grouped).length === 0 ? (
        <EmptyState icon={<BarChart2 className="w-16 h-16"/>} title="No reports found" description="Try adjusting your search or category filter"/>
      ) : (
        (Object.entries(grouped) as [string, any[]][]).map(([cat, catReports]) => (
          <div key={cat}>
            <div className="flex items-center gap-2 mb-3">
              <div className="text-primary">{CATEGORY_ICONS[cat] ?? <FileText className="w-5 h-5"/>}</div>
              <h3 className="font-semibold">{cat.replace(/_/g,' ')}</h3>
              <Badge variant="default">{catReports.length}</Badge>
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3">
              {catReports.map((r: any) => (
                <div key={r.id} className="bg-card border rounded-xl p-4 hover:shadow-md transition-shadow group">
                  <div className="flex items-start justify-between mb-2">
                    <div className="w-9 h-9 rounded-lg bg-primary/10 text-primary flex items-center justify-center group-hover:bg-primary group-hover:text-primary-foreground transition-colors">
                      {CATEGORY_ICONS[cat] ?? <FileText className="w-4 h-4"/>}
                    </div>
                    {r.isSystem && <Badge variant="info">System</Badge>}
                  </div>
                  <h4 className="font-medium text-sm mb-1">{r.name}</h4>
                  {r.description && <p className="text-xs text-muted-foreground mb-3 line-clamp-2">{r.description}</p>}
                  <div className="flex items-center gap-1.5 mt-auto">
                    <Button size="xs" variant="outline" icon={<Download className="w-3 h-3"/>}
                      loading={running === r.id}
                      onClick={() => runReport(r, 'EXCEL')}
                    >
                      Excel
                    </Button>
                    <Button size="xs" variant="outline" icon={<Download className="w-3 h-3"/>}
                      onClick={() => runReport(r, 'PDF')}
                    >
                      PDF
                    </Button>
                    <Button size="xs" variant="ghost" icon={<Calendar className="w-3 h-3"/>} title="Schedule">
                      Schedule
                    </Button>
                  </div>
                </div>
              ))}
            </div>
          </div>
        ))
      )}
    </div>
  )
}
