'use client'

import { useState, useMemo, useCallback } from'react'
import { createClient } from'@/lib/supabase/client'
import { logger } from'@/lib/logger'
import { Download, RefreshCw } from'lucide-react'
import type { Consultant, AppointmentType, PlanningProject, Assignment } from'@/lib/planning-types'
import type { PlanningPerms } from'@/lib/planning-permissions'
import { WORK_MODE_LABELS, WORK_MODE_COLORS, STATUS_COLORS } from'@/lib/planning-config'
import {
 BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend,
 PieChart, Pie, Cell, ResponsiveContainer,
} from'recharts'
import ProjectHeatmap from'./project-heatmap'

interface Props {
 consultants: Consultant[]
 appointmentTypes: AppointmentType[]
 planningProjects: PlanningProject[]
 initialAssignments: Assignment[]
 initialStartDate: string
 initialEndDate: string
 perms: PlanningPerms
}

const CHART_COLORS = ['var(--primary)','#65A30D','#EAB308','#DC2626','#8B5CF6','#06B6D4','#F97316','#EC4899']

export default function ReportsClient({
 consultants, appointmentTypes, planningProjects,
 initialAssignments, initialStartDate, initialEndDate, perms,
}: Props) {
 const [assignments, setAssignments] = useState<Assignment[]>(initialAssignments)
 const [startDate, setStartDate] = useState(initialStartDate)
 const [endDate, setEndDate] = useState(initialEndDate)
 const [loading, setLoading] = useState(false)
 const canSeeGlobal = perms.role ==='admin'|| perms.role ==='team_lead'
 const [reportView, setReportView] = useState<'mine'|'all'>(canSeeGlobal ?'all':'mine')

 const visibleAssignments = useMemo(() => {
 if (reportView ==='mine'&& perms.consultantId) {
 return assignments.filter((a) => a.consultant_id === perms.consultantId)
 }
 return assignments
 }, [assignments, reportView, perms.consultantId])

 const consultantMap = useMemo(() => new Map(consultants.map((c) => [c.id, c])), [consultants])
 const typeMap = useMemo(() => new Map(appointmentTypes.map((t) => [t.id, t])), [appointmentTypes])
 const projectMap = useMemo(() => new Map(planningProjects.map((p) => [p.id, p])), [planningProjects])

 // ── Refresh ────────────────────────────────────────────────────────────────
 async function fetchData() {
 setLoading(true)
 const supabase = createClient()
 const { data, error } = await supabase
 .from('assignments')
 .select('*')
 .gte('date', startDate)
 .lte('date', endDate)
 if (error) logger.error('planning.reports.assignments.fetch_failed', error, { start_date: startDate, end_date: endDate })
 setAssignments((data as Assignment[]) ?? [])
 setLoading(false)
 }

 // ── Chart data ─────────────────────────────────────────────────────────────

 // Booked days per consultant
 const consultantDays = useMemo(() => {
 const counts: Record<string, number> = {}
 for (const a of visibleAssignments) {
 counts[a.consultant_id] = (counts[a.consultant_id] ?? 0) + 1
 }
 return consultants
 .map((c) => ({ name: c.display_name, days: counts[c.id] ?? 0 }))
 .filter((r) => r.days > 0)
 .sort((a, b) => b.days - a.days)
 }, [visibleAssignments, consultants])

 // Booked days per project
 const projectDays = useMemo(() => {
 const counts: Record<string, number> = {}
 for (const a of visibleAssignments) {
 if (a.project_id) counts[a.project_id] = (counts[a.project_id] ?? 0) + 1
 }
 return planningProjects
 .map((p) => ({ name: `${p.code} ${p.name}`, code: p.code, days: counts[p.id] ?? 0 }))
 .filter((r) => r.days > 0)
 .sort((a, b) => b.days - a.days)
 .slice(0, 15)
 }, [visibleAssignments, planningProjects])

 // Appointment type distribution
 const typeDist = useMemo(() => {
 const counts: Record<string, number> = {}
 for (const a of visibleAssignments) {
 counts[a.appointment_type_id] = (counts[a.appointment_type_id] ?? 0) + 1
 }
 return appointmentTypes
 .map((t) => ({ name: t.label, value: counts[t.id] ?? 0, color: t.color }))
 .filter((r) => r.value > 0)
 }, [visibleAssignments, appointmentTypes])

 // Work mode distribution
 const workModeDist = useMemo(() => {
 const counts: Record<string, number> = {}
 for (const a of visibleAssignments) {
 counts[a.work_mode] = (counts[a.work_mode] ?? 0) + 1
 }
 return Object.entries(WORK_MODE_LABELS).map(([k, label]) => ({
 name: label,
 value: counts[k] ?? 0,
 color: WORK_MODE_COLORS[k as keyof typeof WORK_MODE_COLORS],
 })).filter((r) => r.value > 0)
 }, [visibleAssignments])

 // Team utilization by week — stacked bar
 const weekUtilization = useMemo(() => {
 const buckets: Record<string, Record<string, number>> = {}
 for (const a of visibleAssignments) {
 const yw = `${a.date.slice(0, 7)}` // YYYY-MM for simplicity
 if (!buckets[yw]) buckets[yw] = {}
 const teamCode = consultantMap.get(a.consultant_id)?.team_code ??'?'
 buckets[yw][teamCode] = (buckets[yw][teamCode] ?? 0) + 1
 }
 return Object.entries(buckets)
 .sort(([a], [b]) => a.localeCompare(b))
 .map(([month, teams]) => ({ month, ...teams }))
 }, [visibleAssignments, consultantMap])

 const teamCodes = useMemo(
 () => Array.from(new Set(consultants.map((c) => c.team_code))).sort(),
 [consultants],
 )

 // Absence overview per consultant (days without any assignment)
 const absenceDays = useMemo(() => {
 const assignedDays = new Set(visibleAssignments.map((a) => `${a.consultant_id}:${a.date}`))
 const result: { name: string; booked: number; total: number }[] = []
 const s = new Date(startDate +'T00:00:00')
 const e = new Date(endDate +'T00:00:00')
 let totalWeekdays = 0
 for (let d = new Date(s); d <= e; d.setDate(d.getDate() + 1)) {
 const dow = d.getDay()
 if (dow !== 0 && dow !== 6) totalWeekdays++
 }
 for (const c of consultants) {
 const booked = Array.from(assignedDays).filter((k) => k.startsWith(c.id +':')).length
 result.push({ name: c.display_name, booked, total: totalWeekdays })
 }
 return result.filter((r) => r.booked > 0 || r.total > 0).sort((a, b) => b.booked - a.booked)
 }, [visibleAssignments, consultants, startDate, endDate])

 // ── Excel export ───────────────────────────────────────────────────────────
 async function handleExport() {
 const ExcelJS = (await import('exceljs')).default
 const wb = new ExcelJS.Workbook()

 // Sheet 1: Raw assignments
 const ws1 = wb.addWorksheet('Einsätze')
 ws1.columns = [
 { header:'Datum', key:'date', width: 14 },
 { header:'Mitarbeiter', key:'consultant', width: 22 },
 { header:'Team', key:'team', width: 12 },
 { header:'Auftragsart', key:'type', width: 20 },
 { header:'Projekt', key:'project', width: 16 },
 { header:'Kunde', key:'supplier', width: 22 },
 { header:'Ort', key:'location', width: 20 },
 { header:'Arbeitsort', key:'workmode', width: 14 },
 { header:'Status', key:'status', width: 12 },
 ]
 const headerRow = ws1.getRow(1)
 headerRow.eachCell((cell) => {
 cell.fill = { type:'pattern', pattern:'solid', fgColor: { argb:'FF0066B1'} }
 cell.font = { bold: true, color: { argb:'FFFFFFFF'}, size: 10 }
 cell.alignment = { vertical:'middle', horizontal:'center'}
 })
 ws1.views = [{ state:'frozen', ySplit: 1 }]
 for (const a of visibleAssignments) {
 const c = consultantMap.get(a.consultant_id)
 const p = a.project_id ? projectMap.get(a.project_id) : null
 const t = typeMap.get(a.appointment_type_id)
 ws1.addRow({
 date: a.date,
 consultant: c?.display_name ??'',
 team: c?.team_code ??'',
 type: t?.label ??'',
 project: p ? `${p.code} ${p.name}` :'',
 supplier: a.supplier_name ??'',
 location: a.location_label ??'',
 workmode: WORK_MODE_LABELS[a.work_mode],
 status: a.status,
 })
 }

 // Sheet 2: Days per consultant
 const ws2 = wb.addWorksheet('Tage pro Mitarbeiter')
 ws2.columns = [
 { header:'Mitarbeiter', key:'name', width: 25 },
 { header:'Gebuchte Tage', key:'days', width: 16 },
 ]
 ws2.getRow(1).eachCell((cell) => {
 cell.fill = { type:'pattern', pattern:'solid', fgColor: { argb:'FF0066B1'} }
 cell.font = { bold: true, color: { argb:'FFFFFFFF'} }
 })
 consultantDays.forEach((r) => ws2.addRow(r))

 const buf = await wb.xlsx.writeBuffer()
 const blob = new Blob([buf], { type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'})
 const url = URL.createObjectURL(blob)
 const a = document.createElement('a')
 a.href = url
 a.download = `Einsatzplanung_${startDate}_${endDate}.xlsx`
 a.click()
 URL.revokeObjectURL(url)
 }

 const inputCls ='h-8 rounded border border-muted text-[13px] text-foreground px-2 bg-card focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary'

 return (
 <div className="flex-1 overflow-y-auto bg-muted">
 {/* Controls */}
 <div className="bg-card border-b border-muted px-6 py-3 flex flex-wrap items-center gap-3">
 {canSeeGlobal && (
 <div className="flex rounded border border-muted overflow-hidden h-8 shrink-0">
 <button
 onClick={() => setReportView('mine')}
 className={`px-3 text-[12px] font-medium transition-colors ${reportView ==='mine'?'bg-primary text-white':'bg-card text-muted-foreground hover:bg-muted'}`}
 >
 Meine Auswertung
 </button>
 <button
 onClick={() => setReportView('all')}
 className={`px-3 text-[12px] font-medium transition-colors border-l border-muted ${reportView ==='all'?'bg-primary text-white':'bg-card text-muted-foreground hover:bg-muted'}`}
 >
 Globale Auswertung
 </button>
 </div>
 )}
 <label className="text-[12px] font-medium text-foreground">Von</label>
 <input type="date"value={startDate} onChange={(e) => setStartDate(e.target.value)} className={inputCls} />
 <label className="text-[12px] font-medium text-foreground">Bis</label>
 <input type="date"value={endDate} onChange={(e) => setEndDate(e.target.value)} className={inputCls} />
 <button
 onClick={fetchData}
 disabled={loading}
 className="h-8 px-3 flex items-center gap-1.5 text-[13px] font-medium rounded bg-primary text-white hover:bg-primary-dark disabled:opacity-50 transition-colors"
 >
 <RefreshCw size={13} className={loading ?'animate-spin':''} />
 Aktualisieren
 </button>
 <div className="ml-auto">
 <button
 onClick={handleExport}
 className="h-8 px-3 flex items-center gap-1.5 text-[13px] font-medium rounded border border-muted text-foreground hover:bg-muted transition-colors"
 >
 <Download size={13} />
 Excel exportieren
 </button>
 </div>
 </div>

 {/* Summary cards */}
 <div className="px-6 py-4 grid grid-cols-2 md:grid-cols-4 gap-4">
 {[
 { label:'Gesamt Einsätze', value: visibleAssignments.length },
 { label:'Aktive Mitarbeiter', value: new Set(visibleAssignments.map((a) => a.consultant_id)).size },
 { label:'Projekte gebucht', value: new Set(visibleAssignments.filter((a) => a.project_id).map((a) => a.project_id)).size },
 { label:'Zeitraum (Tage)', value: Math.round((new Date(endDate).getTime() - new Date(startDate).getTime()) / 86400000) },
 ].map((s) => (
 <div key={s.label} className="bg-card rounded-xl border border-muted px-4 py-3">
 <p className="text-[11px] text-muted-foreground font-medium">{s.label}</p>
 <p className="text-[28px] font-bold text-primary leading-tight">{s.value}</p>
 </div>
 ))}
 </div>

 <div className="px-6 pb-6 grid grid-cols-1 lg:grid-cols-2 gap-6">

 {/* Booked days per consultant */}
 <div className="bg-card rounded-xl border border-muted p-4">
 <h3 className="text-[13px] font-semibold text-foreground mb-3">Gebuchte Tage pro Mitarbeiter</h3>
 <ResponsiveContainer width="100%"height={Math.max(200, consultantDays.length * 28)}>
 <BarChart data={consultantDays} layout="vertical"margin={{ left: 8, right: 24, top: 4, bottom: 4 }}>
 <CartesianGrid strokeDasharray="3 3"stroke="#F0F0F0"horizontal={false} />
 <XAxis type="number"tick={{ fontSize: 11 }} />
 <YAxis type="category"dataKey="name"width={130} tick={{ fontSize: 11 }} />
 <Tooltip contentStyle={{ fontSize: 12 }} />
 <Bar dataKey="days"name="Tage"fill="var(--primary)"radius={[0, 3, 3, 0]} />
 </BarChart>
 </ResponsiveContainer>
 </div>

 {/* Booked days per project */}
 <div className="bg-card rounded-xl border border-muted p-4">
 <h3 className="text-[13px] font-semibold text-foreground mb-3">Gebuchte Tage pro Projekt (Top 15)</h3>
 {projectDays.length === 0 ? (
 <p className="text-[12px] text-muted-foreground italic py-8 text-center">Keine Projektbuchungen</p>
 ) : (
 <ResponsiveContainer width="100%"height={Math.max(200, projectDays.length * 28)}>
 <BarChart data={projectDays} layout="vertical"margin={{ left: 8, right: 24, top: 4, bottom: 4 }}>
 <CartesianGrid strokeDasharray="3 3"stroke="#F0F0F0"horizontal={false} />
 <XAxis type="number"tick={{ fontSize: 11 }} />
 <YAxis type="category"dataKey="code"width={80} tick={{ fontSize: 11 }} />
 <Tooltip contentStyle={{ fontSize: 12 }} formatter={(v, _, p) => [v, p.payload.name]} />
 <Bar dataKey="days"name="Tage"fill="#65A30D"radius={[0, 3, 3, 0]} />
 </BarChart>
 </ResponsiveContainer>
 )}
 </div>

 {/* Appointment type distribution */}
 <div className="bg-card rounded-xl border border-muted p-4">
 <h3 className="text-[13px] font-semibold text-foreground mb-3">Auftragsart-Verteilung</h3>
 {typeDist.length === 0 ? (
 <p className="text-[12px] text-muted-foreground italic py-8 text-center">Keine Daten</p>
 ) : (
 <div className="flex items-center gap-4">
 <PieChart width={180} height={180}>
 <Pie data={typeDist} cx={85} cy={85} innerRadius={50} outerRadius={80} dataKey="value"paddingAngle={2}>
 {typeDist.map((entry, i) => (
 <Cell key={i} fill={entry.color} />
 ))}
 </Pie>
 <Tooltip contentStyle={{ fontSize: 12 }} />
 </PieChart>
 <div className="space-y-1.5 flex-1">
 {typeDist.map((e) => (
 <div key={e.name} className="flex items-center gap-2 text-[12px]">
 <span className="w-3 h-3 rounded-sm shrink-0"style={{ backgroundColor: e.color }} />
 <span className="flex-1 text-foreground">{e.name}</span>
 <span className="font-medium text-muted-foreground">{e.value}</span>
 </div>
 ))}
 </div>
 </div>
 )}
 </div>

 {/* Work mode distribution */}
 <div className="bg-card rounded-xl border border-muted p-4">
 <h3 className="text-[13px] font-semibold text-foreground mb-3">Arbeitsort-Verteilung</h3>
 {workModeDist.length === 0 ? (
 <p className="text-[12px] text-muted-foreground italic py-8 text-center">Keine Daten</p>
 ) : (
 <div className="flex items-center gap-4">
 <PieChart width={180} height={180}>
 <Pie data={workModeDist} cx={85} cy={85} innerRadius={50} outerRadius={80} dataKey="value"paddingAngle={2}>
 {workModeDist.map((entry, i) => (
 <Cell key={i} fill={entry.color} />
 ))}
 </Pie>
 <Tooltip contentStyle={{ fontSize: 12 }} />
 </PieChart>
 <div className="space-y-1.5 flex-1">
 {workModeDist.map((e) => (
 <div key={e.name} className="flex items-center gap-2 text-[12px]">
 <span className="w-2.5 h-2.5 rounded-full shrink-0"style={{ backgroundColor: e.color }} />
 <span className="flex-1 text-foreground">{e.name}</span>
 <span className="font-medium text-muted-foreground">{e.value}</span>
 </div>
 ))}
 </div>
 </div>
 )}
 </div>

 {/* Team utilization by month */}
 <div className="bg-card rounded-xl border border-muted p-4 lg:col-span-2">
 <h3 className="text-[13px] font-semibold text-foreground mb-3">Team-Auslastung pro Monat</h3>
 {weekUtilization.length === 0 ? (
 <p className="text-[12px] text-muted-foreground italic py-8 text-center">Keine Daten</p>
 ) : (
 <ResponsiveContainer width="100%"height={220}>
 <BarChart data={weekUtilization} margin={{ left: 0, right: 16, top: 4, bottom: 4 }}>
 <CartesianGrid strokeDasharray="3 3"stroke="#F0F0F0"/>
 <XAxis dataKey="month"tick={{ fontSize: 11 }} />
 <YAxis tick={{ fontSize: 11 }} />
 <Tooltip contentStyle={{ fontSize: 12 }} />
 <Legend wrapperStyle={{ fontSize: 11 }} />
 {teamCodes.map((tc, i) => (
 <Bar key={tc} dataKey={tc} stackId="a"name={tc} fill={CHART_COLORS[i % CHART_COLORS.length]} />
 ))}
 </BarChart>
 </ResponsiveContainer>
 )}
 </div>

 {/* Project heatmap */}
 <div className="bg-card rounded-xl border border-muted p-4 lg:col-span-2">
 <h3 className="text-[13px] font-semibold text-foreground mb-3">Projekt-Heatmap (letzte 16 Wochen)</h3>
 <ProjectHeatmap assignments={visibleAssignments} projects={planningProjects} weekCount={16} />
 </div>

 {/* Absence overview */}
 <div className="bg-card rounded-xl border border-muted p-4 lg:col-span-2">
 <h3 className="text-[13px] font-semibold text-foreground mb-3">
 Buchungsübersicht pro Mitarbeiter ({startDate} – {endDate})
 </h3>
 <div className="overflow-x-auto">
 <table className="w-full text-[12px] border-collapse">
 <thead>
 <tr className="border-b-2 border-muted bg-muted">
 <th className="text-left px-3 py-2 font-semibold text-foreground">Mitarbeiter</th>
 <th className="text-right px-3 py-2 font-semibold text-foreground">Gebucht</th>
 <th className="text-right px-3 py-2 font-semibold text-foreground">Arbeitstage</th>
 <th className="text-right px-3 py-2 font-semibold text-foreground">Quote</th>
 <th className="px-3 py-2">Auslastung</th>
 </tr>
 </thead>
 <tbody>
 {absenceDays.map((r, i) => {
 const pct = r.total > 0 ? Math.round((r.booked / r.total) * 100) : 0
 return (
 <tr key={r.name} className={i % 2 === 0 ?'bg-card':'bg-background'}>
 <td className="px-3 py-1.5 font-medium text-foreground">{r.name}</td>
 <td className="px-3 py-1.5 text-right text-foreground">{r.booked}</td>
 <td className="px-3 py-1.5 text-right text-muted-foreground">{r.total}</td>
 <td className="px-3 py-1.5 text-right font-medium"style={{ color: pct >= 80 ?'#65A30D': pct >= 50 ?'#EAB308':'#DC2626'}}>
 {pct}%
 </td>
 <td className="px-3 py-1.5 w-48">
 <div className="h-2 bg-[#E5E5E5] rounded-full overflow-hidden">
 <div
 className="h-full rounded-full transition-all"
 style={{
 width: `${pct}%`,
 backgroundColor: pct >= 80 ?'#65A30D': pct >= 50 ?'#EAB308':'#DC2626',
 }}
 />
 </div>
 </td>
 </tr>
 )
 })}
 </tbody>
 </table>
 </div>
 </div>
 </div>
 </div>
 )
}
