"use client";

import * as React from "react";
import { useQuery } from "@tanstack/react-query";
import { useSession } from "next-auth/react";
import {
  ResponsiveContainer,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  Tooltip,
  PieChart,
  Pie,
  Cell,
  Legend,
} from "recharts";
import Link from "next/link";
import { Download, Printer, FileBarChart } from "lucide-react";
import { apiGet } from "@/lib/api";
import type { ReportDTO, CompanyDTO, DepartmentDTO } from "@/lib/types";
import { isManagerTier, MARKETING_POSITIONS } from "@/lib/rbac";
import { formatMetric } from "@/lib/utils";
import { STATUS_LABEL, CHANNEL_LABEL } from "@/lib/labels";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Select } from "@/components/ui/select";
import { Progress } from "@/components/ui/progress";
import { PageHeader, StatCard, Spinner, EmptyState } from "@/components/common";

const CHANNELS = ["META", "GOOGLE", "TIKTOK", "OFFLINE", "SEO", "EMAIL", "OTHER"];
const PIE_COLORS = ["#94a3b8", "#6366f1", "#f59e0b", "#a855f7", "#16a34a"];

export function ReportsView() {
  const { data: session } = useSession();
  const manager = isManagerTier(session?.user?.role);

  const [from, setFrom] = React.useState("");
  const [to, setTo] = React.useState("");
  const [channel, setChannel] = React.useState("");
  const [position, setPosition] = React.useState("");
  const [companyId, setCompanyId] = React.useState("");
  const [departmentId, setDepartmentId] = React.useState("");

  const companies = useQuery({
    queryKey: ["companies"],
    queryFn: () => apiGet<CompanyDTO[]>("/api/companies"),
    enabled: manager,
  });
  const departments = useQuery({
    queryKey: ["departments"],
    queryFn: () => apiGet<DepartmentDTO[]>("/api/departments"),
    enabled: manager,
  });

  const params = new URLSearchParams();
  if (from) params.set("from", from);
  if (to) params.set("to", to);
  if (channel) params.set("channel", channel);
  if (position) params.set("position", position);
  if (companyId) params.set("companyId", companyId);
  if (departmentId) params.set("departmentId", departmentId);
  const qs = params.toString();

  const report = useQuery({
    queryKey: ["reports", qs],
    queryFn: () => apiGet<ReportDTO>(`/api/reports${qs ? `?${qs}` : ""}`),
    enabled: manager,
  });

  if (!manager) {
    return (
      <EmptyState
        title="Manager access required"
        description="Reports are available to Manager, Admin and Super Admin roles."
      />
    );
  }

  const data = report.data;

  function exportCsv() {
    if (!data) return;
    const rows = [
      ["Staff", "Position", "Tasks Total", "Tasks Completed", "KPI Delta"],
      ...data.matrix.map((m) => [
        m.name,
        m.position ?? "",
        m.tasksTotal,
        m.tasksCompleted,
        m.totalDelta,
      ]),
    ];
    const csv = rows.map((r) => r.map((c) => `"${String(c).replace(/"/g, '""')}"`).join(",")).join("\n");
    const a = document.createElement("a");
    a.href = "data:text/csv;charset=utf-8," + encodeURIComponent(csv);
    const range = from || to ? `${from || "start"}_to_${to || "now"}` : "all-time";
    a.download = `marketing-report-${range}.csv`;
    a.click();
  }

  return (
    <div>
      <PageHeader title="Reports & Analytics" subtitle="Live team performance — actual vs targets">
        <Link href="/reports/monthly">
          <Button variant="secondary">
            <FileBarChart className="size-4" /> Monthly KPI Report
          </Button>
        </Link>
        <Button variant="secondary" onClick={exportCsv}>
          <Download className="size-4" /> CSV
        </Button>
        <Button variant="secondary" onClick={() => window.print()}>
          <Printer className="size-4" /> PDF
        </Button>
      </PageHeader>

      {/* Filters */}
      <div className="no-print mb-4 flex flex-wrap items-center gap-2">
        <div className="flex items-center gap-1.5">
          <span className="text-xs text-muted-foreground">From</span>
          <Input
            type="date"
            className="h-8 w-auto text-xs"
            value={from}
            max={to || undefined}
            onChange={(e) => setFrom(e.target.value)}
          />
        </div>
        <div className="flex items-center gap-1.5">
          <span className="text-xs text-muted-foreground">To</span>
          <Input
            type="date"
            className="h-8 w-auto text-xs"
            value={to}
            min={from || undefined}
            onChange={(e) => setTo(e.target.value)}
          />
        </div>
        {(from || to) && (
          <Button
            variant="secondary"
            className="h-8 text-xs"
            onClick={() => {
              setFrom("");
              setTo("");
            }}
          >
            Clear dates
          </Button>
        )}
        <Select className="h-8 w-auto text-xs" value={departmentId} onChange={(e) => setDepartmentId(e.target.value)}>
          <option value="">All departments</option>
          {(departments.data ?? []).map((d) => (
            <option key={d.id} value={d.id}>
              {d.name}
            </option>
          ))}
        </Select>
        <Select className="h-8 w-auto text-xs" value={companyId} onChange={(e) => setCompanyId(e.target.value)}>
          <option value="">All companies</option>
          {(companies.data ?? []).map((c) => (
            <option key={c.id} value={c.id}>
              {c.name}
            </option>
          ))}
        </Select>
        <Select className="h-8 w-auto text-xs" value={channel} onChange={(e) => setChannel(e.target.value)}>
          <option value="">All channels</option>
          {CHANNELS.map((c) => (
            <option key={c} value={c}>
              {CHANNEL_LABEL[c]}
            </option>
          ))}
        </Select>
        <Select className="h-8 w-auto text-xs" value={position} onChange={(e) => setPosition(e.target.value)}>
          <option value="">All positions</option>
          {MARKETING_POSITIONS.map((p) => (
            <option key={p} value={p}>
              {p}
            </option>
          ))}
        </Select>
      </div>

      {report.isLoading || !data ? (
        <Spinner />
      ) : (
        <div className="space-y-6">
          <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
            <StatCard label="Team Score" value={`${data.teamScore}%`} accent="primary" hint="weighted KPI"
              info="Weighted department-KPI attainment for the current filters. Each KPI counts in proportion to its weightage (%); 100% = all targets met." />
            <StatCard label="Total Tasks" value={data.totals.tasks}
              info="Tasks matching the current filters (date range, company, department, channel, position)." />
            <StatCard label="Completed" value={data.totals.completed} accent="success"
              info="How many of those tasks are marked Completed." />
            <StatCard label="Active Staff" value={data.totals.staff}
              info="Active staff members included in this filtered view." />
          </div>

          {/* Department KPI progress */}
          <Card>
            <CardHeader>
              <CardTitle>Department KPI — Actual vs Target</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              {data.kpiProgress.length === 0 ? (
                <EmptyState title="No department KPIs match these filters" />
              ) : (
                data.kpiProgress.map((k) => (
                  <div key={k.id}>
                    <div className="mb-1 flex items-center justify-between text-sm">
                      <span className="font-medium">{k.name}</span>
                      <span className="text-muted-foreground">
                        {formatMetric(k.currentValue, k.unit)} / {formatMetric(k.targetValue, k.unit)} ({k.pct}%)
                      </span>
                    </div>
                    <Progress value={k.pct} />
                  </div>
                ))
              )}
            </CardContent>
          </Card>

          <div className="grid gap-4 lg:grid-cols-2">
            {/* Staff matrix chart */}
            <Card>
              <CardHeader>
                <CardTitle>Staff: Completed vs KPI Delta</CardTitle>
              </CardHeader>
              <CardContent>
                {data.matrix.length === 0 ? (
                  <EmptyState title="No staff data" />
                ) : (
                  <ResponsiveContainer width="100%" height={260}>
                    <BarChart data={data.matrix.map((m) => ({ name: m.name.split(" ")[0], Completed: m.tasksCompleted, Delta: m.totalDelta }))}>
                      <XAxis dataKey="name" fontSize={11} stroke="var(--muted-foreground)" />
                      <YAxis fontSize={11} stroke="var(--muted-foreground)" />
                      <Tooltip
                        contentStyle={{
                          background: "var(--card)",
                          border: "1px solid var(--border)",
                          borderRadius: 8,
                          fontSize: 12,
                        }}
                      />
                      <Legend wrapperStyle={{ fontSize: 12 }} />
                      <Bar dataKey="Completed" fill="#6366f1" radius={[4, 4, 0, 0]} />
                      <Bar dataKey="Delta" fill="#16a34a" radius={[4, 4, 0, 0]} />
                    </BarChart>
                  </ResponsiveContainer>
                )}
              </CardContent>
            </Card>

            {/* Status breakdown pie */}
            <Card>
              <CardHeader>
                <CardTitle>Task Status Breakdown</CardTitle>
              </CardHeader>
              <CardContent>
                <ResponsiveContainer width="100%" height={260}>
                  <PieChart>
                    <Pie
                      data={data.statusBreakdown.filter((s) => s.count > 0).map((s) => ({ name: STATUS_LABEL[s.status], value: s.count }))}
                      dataKey="value"
                      nameKey="name"
                      innerRadius={55}
                      outerRadius={90}
                    >
                      {data.statusBreakdown.map((_, i) => (
                        <Cell key={i} fill={PIE_COLORS[i % PIE_COLORS.length]} />
                      ))}
                    </Pie>
                    <Legend wrapperStyle={{ fontSize: 12 }} />
                    <Tooltip
                      contentStyle={{
                        background: "var(--card)",
                        border: "1px solid var(--border)",
                        borderRadius: 8,
                        fontSize: 12,
                      }}
                    />
                  </PieChart>
                </ResponsiveContainer>
              </CardContent>
            </Card>
          </div>

          {/* Side-by-side matrix table */}
          <Card className="overflow-hidden">
            <CardHeader>
              <CardTitle>Staff Performance Matrix</CardTitle>
            </CardHeader>
            <CardContent className="p-0">
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="border-y border-border text-left text-xs uppercase text-muted-foreground">
                      <th className="px-4 py-2.5">Staff</th>
                      <th className="px-4 py-2.5">Position</th>
                      <th className="px-4 py-2.5">Tasks</th>
                      <th className="px-4 py-2.5">Completed</th>
                      <th className="px-4 py-2.5">Completion</th>
                      <th className="px-4 py-2.5">KPI Δ</th>
                    </tr>
                  </thead>
                  <tbody>
                    {data.matrix.map((m) => {
                      const rate = m.tasksTotal ? Math.round((m.tasksCompleted / m.tasksTotal) * 100) : 0;
                      return (
                        <tr key={m.id} className="border-b border-border last:border-0">
                          <td className="px-4 py-2.5 font-medium">{m.name}</td>
                          <td className="px-4 py-2.5 text-muted-foreground">{m.position ?? "—"}</td>
                          <td className="px-4 py-2.5">{m.tasksTotal}</td>
                          <td className="px-4 py-2.5">{m.tasksCompleted}</td>
                          <td className="px-4 py-2.5">
                            <div className="flex items-center gap-2">
                              <Progress value={rate} className="w-20" />
                              <span className="text-xs text-muted-foreground">{rate}%</span>
                            </div>
                          </td>
                          <td className="px-4 py-2.5 font-medium">{formatMetric(m.totalDelta)}</td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            </CardContent>
          </Card>
        </div>
      )}
    </div>
  );
}
