"use client";

import { useState } from "react";

import { AlertTriangle, Eye } from "lucide-react";
import { toast } from "sonner";

import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { Separator } from "@/components/ui/separator";
import { ARCHETYPES } from "@/data/archetypes";
import { DEMO_GLP1_CASES } from "@/data/glp1-cases";
import type { GLP1Case } from "@/types/novalife";

const RISK_COLORS: Record<string, string> = {
  high: "bg-red-100 text-red-700 border-red-200",
  medium: "bg-amber-100 text-amber-700 border-amber-200",
  low: "bg-green-100 text-green-700 border-green-200",
};

const STATUS_COLORS: Record<string, string> = {
  pending_review: "bg-amber-100 text-amber-700",
  reviewed: "bg-green-100 text-green-700",
  notified: "bg-blue-100 text-blue-700",
  referred: "bg-purple-100 text-purple-700",
};

const STATUS_LABELS: Record<string, string> = {
  pending_review: "Pending Review",
  reviewed: "Reviewed",
  notified: "Notified",
  referred: "Referred",
};

export default function GLP1ManagementPage() {
  const [selectedCase, setSelectedCase] = useState<GLP1Case | null>(null);
  const pendingCount = DEMO_GLP1_CASES.filter((c) => c.status === "pending_review").length;
  const highRiskCount = DEMO_GLP1_CASES.filter((c) => c.riskLevel === "high").length;

  return (
    <div className="space-y-6 p-6">
      <div>
        <h1 className="text-2xl font-bold text-gray-900">GLP-1 Eligibility Management</h1>
        <p className="text-sm text-gray-500 mt-1">Monitor and manage GLP-1 eligible users requiring medical referral.</p>
      </div>

      {pendingCount > 0 && (
        <div className="flex items-center gap-3 rounded-xl border border-amber-200 bg-amber-50 p-4">
          <AlertTriangle className="h-5 w-5 text-amber-600 shrink-0" />
          <p className="text-sm font-medium text-amber-800">
            {pendingCount} case{pendingCount > 1 ? "s" : ""} pending review. Please assess these users promptly.
          </p>
        </div>
      )}

      <div className="grid gap-4 sm:grid-cols-3">
        {[
          { label: "Total Eligible", value: DEMO_GLP1_CASES.length, color: "text-teal-600" },
          { label: "High Risk", value: highRiskCount, color: "text-red-600" },
          { label: "Pending Review", value: pendingCount, color: "text-amber-600" },
        ].map((stat) => (
          <Card key={stat.label} className="border-gray-100">
            <CardContent className="p-5">
              <p className="text-sm text-gray-500">{stat.label}</p>
              <p className={`text-3xl font-bold mt-1 ${stat.color}`}>{stat.value}</p>
            </CardContent>
          </Card>
        ))}
      </div>

      <Card className="border-gray-100">
        <CardHeader className="pb-3">
          <CardTitle className="text-base">GLP-1 Eligible Users</CardTitle>
        </CardHeader>
        <CardContent className="p-0">
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="bg-gray-50 border-y border-gray-100">
                <tr>
                  {["User", "BMI", "GLP-1 Score", "Risk", "Archetype", "Status", "Date", "Actions"].map((h) => (
                    <th key={h} className="px-4 py-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wide">
                      {h}
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-50">
                {DEMO_GLP1_CASES.map((c) => {
                  const archetype = ARCHETYPES.find((a) => a.id === c.archetypeId);
                  return (
                    <tr key={c.id} className="hover:bg-gray-50/50">
                      <td className="px-4 py-3">
                        <p className="font-medium text-gray-900">{c.userName}</p>
                        <p className="text-xs text-gray-400">{c.email}</p>
                      </td>
                      <td className="px-4 py-3 font-mono font-medium">{c.bmi}</td>
                      <td className="px-4 py-3">
                        <span className="font-bold text-teal-600">{c.glp1Score}/10</span>
                      </td>
                      <td className="px-4 py-3">
                        <Badge variant="outline" className={RISK_COLORS[c.riskLevel]}>
                          {c.riskLevel}
                        </Badge>
                      </td>
                      <td className="px-4 py-3">
                        {archetype && (
                          <span
                            className="rounded-full px-2.5 py-0.5 text-xs font-medium"
                            style={{ backgroundColor: archetype.bgColor, color: archetype.color }}
                          >
                            {archetype.name}
                          </span>
                        )}
                      </td>
                      <td className="px-4 py-3">
                        <Badge className={STATUS_COLORS[c.status] + " border-0"}>
                          {STATUS_LABELS[c.status]}
                        </Badge>
                      </td>
                      <td className="px-4 py-3 text-gray-400 text-xs">
                        {new Date(c.createdAt).toLocaleDateString()}
                      </td>
                      <td className="px-4 py-3">
                        <Button
                          size="sm"
                          variant="outline"
                          className="h-7 text-xs"
                          onClick={() => setSelectedCase(c)}
                        >
                          <Eye className="h-3 w-3 mr-1" />
                          Review
                        </Button>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>

      <Dialog open={!!selectedCase} onOpenChange={() => setSelectedCase(null)}>
        <DialogContent className="max-w-lg">
          <DialogHeader>
            <DialogTitle>GLP-1 Case Review — {selectedCase?.userName}</DialogTitle>
          </DialogHeader>
          {selectedCase && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-3">
                <div><Label className="text-xs text-gray-500">BMI</Label><p className="font-bold text-lg">{selectedCase.bmi}</p></div>
                <div><Label className="text-xs text-gray-500">GLP-1 Score</Label><p className="font-bold text-lg text-teal-600">{selectedCase.glp1Score}/10</p></div>
              </div>
              <Separator />
              <div>
                <Label className="text-xs text-gray-500 uppercase tracking-wide">Triggered Factors</Label>
                <ul className="mt-2 space-y-1">
                  {selectedCase.triggeredAnswers.map((a) => (
                    <li key={a} className="flex items-start gap-2 text-sm text-gray-700">
                      <span className="text-teal-600 mt-0.5">•</span>{a}
                    </li>
                  ))}
                </ul>
              </div>
              <Separator />
              <div className="flex gap-2">
                <Button className="flex-1 bg-teal-600 hover:bg-teal-700 text-white" onClick={() => { toast.success("Status updated (PoC simulation)"); setSelectedCase(null); }}>
                  Mark as Reviewed
                </Button>
                <Button variant="outline" className="flex-1" onClick={() => { toast.success("Referral notification sent (PoC simulation)"); setSelectedCase(null); }}>
                  Notify & Refer
                </Button>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}
