import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { reportsApi } from '../../api'
import {
  BarChart, Bar, LineChart, Line, PieChart, Pie, Cell,
  XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer,
} from 'recharts'

const MONTH_NAMES = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
const PIE_COLORS = ['#3b82f6','#22c55e','#f59e0b','#ef4444','#8b5cf6','#06b6d4']

function Card({ children, title }: any) {
  return (
    <div className="card space-y-4">
      <h2 className="font-semibold text-white border-b border-slate-700 pb-3">{title}</h2>
      {children}
    </div>
  )
}

export default function ReportsPage() {
  const [tab, setTab]   = useState<'revenue' | 'occupancy' | 'clients' | 'overdue'>('revenue')
  const [from, setFrom] = useState(new Date(new Date().getFullYear(), new Date().getMonth(), 1).toISOString().split('T')[0])
  const [to, setTo]     = useState(new Date().toISOString().split('T')[0])

  const { data: revenueData }   = useQuery({ queryKey: ['report-revenue', from, to], queryFn: () => reportsApi.revenue({ from, to }).then(r => r.data), enabled: tab === 'revenue' })
  const { data: occupancyData } = useQuery({ queryKey: ['report-occupancy'], queryFn: () => reportsApi.occupancy().then(r => r.data), enabled: tab === 'occupancy' })
  const { data: clientsData }   = useQuery({ queryKey: ['report-clients'], queryFn: () => reportsApi.clients().then(r => r.data), enabled: tab === 'clients' })
  const { data: overdueData }   = useQuery({ queryKey: ['report-overdue'], queryFn: () => reportsApi.overdue().then(r => r.data), enabled: tab === 'overdue' })

  const tabs = [
    { key: 'revenue',   label: 'Revenue' },
    { key: 'occupancy', label: 'Occupancy' },
    { key: 'clients',   label: 'Clients' },
    { key: 'overdue',   label: 'Overdue' },
  ]

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between flex-wrap gap-3">
        <div>
          <h1 className="text-2xl font-bold text-white">Reports</h1>
          <p className="text-slate-400 text-sm">Analytics and insights</p>
        </div>
        {(tab === 'revenue' || tab === 'clients') && (
          <div className="flex items-center gap-2">
            <input type="date" value={from} onChange={e => setFrom(e.target.value)} className="input w-40 text-sm" />
            <span className="text-slate-400 text-sm">to</span>
            <input type="date" value={to} onChange={e => setTo(e.target.value)} className="input w-40 text-sm" />
          </div>
        )}
      </div>

      {/* Tabs */}
      <div className="flex gap-1 bg-slate-800 p-1 rounded-xl w-fit">
        {tabs.map(t => (
          <button key={t.key} onClick={() => setTab(t.key as any)}
            className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${tab === t.key ? 'bg-blue-600 text-white' : 'text-slate-400 hover:text-white'}`}>
            {t.label}
          </button>
        ))}
      </div>

      {/* Revenue tab */}
      {tab === 'revenue' && revenueData && (
        <div className="space-y-6">
          {/* KPI summary */}
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
            {(revenueData.summary ?? []).map((s: any) => (
              <div key={s.type} className="card text-center">
                <p className="text-slate-400 text-xs capitalize">{s.type?.replace('_', ' ')}</p>
                <p className="text-xl font-bold text-white mt-1">৳{Number(s.total).toLocaleString()}</p>
                <p className="text-slate-500 text-xs">{s.count} transactions</p>
              </div>
            ))}
          </div>

          {/* Daily revenue line chart */}
          <Card title="Daily Revenue">
            <ResponsiveContainer width="100%" height={260}>
              <LineChart data={revenueData.daily ?? []}>
                <CartesianGrid strokeDasharray="3 3" stroke="#334155" />
                <XAxis dataKey="date" tick={{ fill: '#94a3b8', fontSize: 11 }} />
                <YAxis tick={{ fill: '#94a3b8', fontSize: 11 }} tickFormatter={v => `৳${(v/1000).toFixed(0)}k`} />
                <Tooltip
                  contentStyle={{ background: '#1e293b', border: '1px solid #334155', borderRadius: 8, color: '#f1f5f9' }}
                  formatter={(v: any) => [`৳${Number(v).toLocaleString()}`, 'Revenue']}
                />
                <Line type="monotone" dataKey="total" stroke="#3b82f6" strokeWidth={2} dot={false} />
              </LineChart>
            </ResponsiveContainer>
          </Card>

          {/* Revenue by method pie */}
          {revenueData.byMethod && revenueData.byMethod.length > 0 && (
            <Card title="Revenue by Payment Method">
              <div className="flex items-center gap-6">
                <ResponsiveContainer width="50%" height={200}>
                  <PieChart>
                    <Pie data={revenueData.byMethod} dataKey="total" nameKey="method" cx="50%" cy="50%" outerRadius={80} label={({ method, percent }) => `${method} ${(percent*100).toFixed(0)}%`}>
                      {revenueData.byMethod.map((_: any, i: number) => <Cell key={i} fill={PIE_COLORS[i % PIE_COLORS.length]} />)}
                    </Pie>
                    <Tooltip formatter={(v: any) => `৳${Number(v).toLocaleString()}`} contentStyle={{ background: '#1e293b', border: '1px solid #334155', borderRadius: 8, color: '#f1f5f9' }} />
                  </PieChart>
                </ResponsiveContainer>
                <div className="space-y-2">
                  {revenueData.byMethod.map((m: any, i: number) => (
                    <div key={m.method} className="flex items-center gap-2 text-sm">
                      <div className="w-3 h-3 rounded-full" style={{ background: PIE_COLORS[i % PIE_COLORS.length] }} />
                      <span className="text-slate-300">{m.method}</span>
                      <span className="text-white font-semibold ml-2">৳{Number(m.total).toLocaleString()}</span>
                    </div>
                  ))}
                </div>
              </div>
            </Card>
          )}
        </div>
      )}

      {/* Occupancy tab */}
      {tab === 'occupancy' && occupancyData && (
        <div className="space-y-6">
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
            {[
              { label: 'Total Lockers', value: occupancyData.overview?.total },
              { label: 'Occupied', value: occupancyData.overview?.occupied },
              { label: 'Available', value: occupancyData.overview?.available },
              { label: 'Occupancy Rate', value: `${occupancyData.overview?.occupancy_rate ?? 0}%` },
            ].map(({ label, value }) => (
              <div key={label} className="card text-center">
                <p className="text-slate-400 text-xs">{label}</p>
                <p className="text-2xl font-bold text-white mt-1">{value}</p>
              </div>
            ))}
          </div>

          <Card title="Occupancy by Category">
            <ResponsiveContainer width="100%" height={240}>
              <BarChart data={occupancyData.byCategory ?? []}>
                <CartesianGrid strokeDasharray="3 3" stroke="#334155" />
                <XAxis dataKey="category" tick={{ fill: '#94a3b8', fontSize: 12 }} />
                <YAxis tick={{ fill: '#94a3b8', fontSize: 12 }} />
                <Tooltip contentStyle={{ background: '#1e293b', border: '1px solid #334155', borderRadius: 8, color: '#f1f5f9' }} />
                <Legend />
                <Bar dataKey="total" fill="#475569" name="Total" radius={[4,4,0,0]} />
                <Bar dataKey="occupied" fill="#3b82f6" name="Occupied" radius={[4,4,0,0]} />
              </BarChart>
            </ResponsiveContainer>
          </Card>

          <Card title="Occupancy by Zone">
            <ResponsiveContainer width="100%" height={240}>
              <BarChart data={occupancyData.byZone ?? []}>
                <CartesianGrid strokeDasharray="3 3" stroke="#334155" />
                <XAxis dataKey="zone" tick={{ fill: '#94a3b8', fontSize: 12 }} />
                <YAxis tick={{ fill: '#94a3b8', fontSize: 12 }} />
                <Tooltip contentStyle={{ background: '#1e293b', border: '1px solid #334155', borderRadius: 8, color: '#f1f5f9' }} />
                <Legend />
                <Bar dataKey="total" fill="#475569" name="Total" radius={[4,4,0,0]} />
                <Bar dataKey="occupied" fill="#22c55e" name="Occupied" radius={[4,4,0,0]} />
              </BarChart>
            </ResponsiveContainer>
          </Card>
        </div>
      )}

      {/* Clients tab */}
      {tab === 'clients' && clientsData && (
        <div className="space-y-6">
          <div className="grid grid-cols-3 gap-4">
            {(clientsData.byStatus ?? []).map((s: any) => (
              <div key={s.status} className="card text-center">
                <p className="text-slate-400 text-xs capitalize">{s.status}</p>
                <p className="text-2xl font-bold text-white mt-1">{s.total}</p>
              </div>
            ))}
          </div>

          <Card title="New Registrations Over Time">
            <ResponsiveContainer width="100%" height={260}>
              <BarChart data={(clientsData.newPerMonth ?? []).map((m: any) => ({ ...m, label: `${MONTH_NAMES[m.month - 1]} ${m.year}` }))}>
                <CartesianGrid strokeDasharray="3 3" stroke="#334155" />
                <XAxis dataKey="label" tick={{ fill: '#94a3b8', fontSize: 11 }} />
                <YAxis tick={{ fill: '#94a3b8', fontSize: 11 }} />
                <Tooltip contentStyle={{ background: '#1e293b', border: '1px solid #334155', borderRadius: 8, color: '#f1f5f9' }} />
                <Bar dataKey="total" fill="#3b82f6" name="New Clients" radius={[4,4,0,0]} />
              </BarChart>
            </ResponsiveContainer>
          </Card>
        </div>
      )}

      {/* Overdue tab */}
      {tab === 'overdue' && overdueData && (
        <div className="space-y-4">
          <div className="card bg-red-900/20 border-red-800">
            <p className="text-red-300 font-semibold text-lg">{overdueData.total ?? 0} overdue rentals</p>
            <p className="text-slate-400 text-sm mt-1">These clients need to renew or return their lockers.</p>
          </div>
          <div className="card p-0 overflow-hidden">
            <table className="w-full">
              <thead className="border-b border-slate-700">
                <tr className="text-left text-xs text-slate-400 uppercase tracking-wider">
                  <th className="px-4 py-3">Client</th>
                  <th className="px-4 py-3">Phone</th>
                  <th className="px-4 py-3">Locker</th>
                  <th className="px-4 py-3">Expired</th>
                  <th className="px-4 py-3">Days Overdue</th>
                  <th className="px-4 py-3">Amount</th>
                  <th className="px-4 py-3">Key</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-700/50">
                {(overdueData.overdue ?? []).map((r: any, i: number) => (
                  <tr key={i} className="hover:bg-slate-700/30">
                    <td className="px-4 py-3 text-sm font-medium text-white">{r.client_name}</td>
                    <td className="px-4 py-3 text-sm text-slate-300">{r.client_phone}</td>
                    <td className="px-4 py-3 font-mono text-sm text-slate-300">{r.locker_number}</td>
                    <td className="px-4 py-3 text-sm text-red-400">{r.end_date}</td>
                    <td className="px-4 py-3 text-sm font-bold text-red-400">{r.days_overdue}d</td>
                    <td className="px-4 py-3 text-sm text-white">৳{Number(r.rental_amount).toLocaleString()}</td>
                    <td className="px-4 py-3 text-xs text-slate-400">{r.key_status?.replace('_', ' ')}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  )
}
