"use client";

import { Edit2, FileText, RefreshCw } from "lucide-react";
import { useState } from "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,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Textarea } from "@/components/ui/textarea";
import { ARCHETYPES } from "@/data/archetypes";
import { DEMO_USERS } from "@/data/users";

const TIERS = ["starter", "advanced", "professional"] as const;
type Tier = typeof TIERS[number];

interface ReportTemplate {
  archetypeId: string;
  archetypeName: string;
  archetypeColor: string;
  tier: Tier;
}

const REPORT_TEMPLATES: ReportTemplate[] = ARCHETYPES.flatMap((a) =>
  TIERS.map((tier) => ({
    archetypeId: a.id,
    archetypeName: a.name,
    archetypeColor: a.color,
    tier,
  })),
);

// Build demo generated reports from users who have report IDs
const DEMO_REPORTS = DEMO_USERS.filter((u) => u.reportIds.length > 0 && u.archetypeResult).map((u) => ({
  id: u.reportIds[0],
  userId: u.id,
  userName: `${u.firstName} ${u.lastName}`,
  userEmail: u.email,
  archetypeId: u.archetypeResult!.primaryArchetype,
  tier: u.purchasedPackage ?? "starter",
  generatedAt: u.archetypeResult!.completedAt,
}));

const TIER_STYLES: Record<Tier, string> = {
  starter: "bg-blue-50 text-blue-700 border-blue-200",
  advanced: "bg-teal-50 text-teal-700 border-teal-200",
  professional: "bg-violet-50 text-violet-700 border-violet-200",
};

function EditTemplateDialog({
  template,
  open,
  onClose,
}: {
  template: ReportTemplate;
  open: boolean;
  onClose: () => void;
}) {
  return (
    <Dialog open={open} onOpenChange={onClose}>
      <DialogContent className="max-w-2xl max-h-[80vh] overflow-y-auto">
        <DialogHeader>
          <div className="flex items-center gap-3">
            <div
              className="h-7 w-7 rounded-lg"
              style={{ backgroundColor: template.archetypeColor }}
            />
            <DialogTitle>
              {template.archetypeName} · {template.tier} template
            </DialogTitle>
          </div>
        </DialogHeader>

        <div className="space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <div>
              <Label className="text-xs">Archetype Profile — Intro</Label>
              <Textarea
                placeholder="Opening section content for this archetype..."
                className="mt-1 text-sm resize-none"
                rows={4}
                defaultValue={`Personalized archetype profile for ${template.archetypeName} (${template.tier} tier)...`}
              />
            </div>
            <div>
              <Label className="text-xs">Metabolic Snapshot</Label>
              <Textarea
                placeholder="Metabolic snapshot content..."
                className="mt-1 text-sm resize-none"
                rows={4}
                defaultValue={`Metabolic snapshot content tailored for the ${template.tier} tier...`}
              />
            </div>
          </div>

          <div>
            <Label className="text-xs">Why You Struggle Section</Label>
            <Textarea
              placeholder="Root cause analysis content..."
              className="mt-1 text-sm resize-none"
              rows={5}
              defaultValue={`Root cause analysis for ${template.archetypeName}. In ${template.tier} tier, this section includes additional depth...`}
            />
          </div>

          <div>
            <Label className="text-xs">Nutrition Strategy</Label>
            <Textarea
              placeholder="Nutrition recommendations..."
              className="mt-1 text-sm resize-none"
              rows={4}
              defaultValue="Personalized nutrition strategy content goes here..."
            />
          </div>

          {(template.tier === "advanced" || template.tier === "professional") && (
            <div>
              <Label className="text-xs">GLP-1 Assessment Section</Label>
              <Input defaultValue="GLP-1 eligibility assessment and next steps..." className="text-sm" />
            </div>
          )}

          {template.tier === "professional" && (
            <div>
              <Label className="text-xs">90-Day Action Plan</Label>
              <Textarea
                placeholder="Professional action plan..."
                className="mt-1 text-sm resize-none"
                rows={5}
                defaultValue="Comprehensive 90-day personalized action plan for Professional tier..."
              />
            </div>
          )}
        </div>

        <DialogFooter>
          <Button variant="outline" size="sm" onClick={onClose}>Cancel</Button>
          <Button
            size="sm"
            className="bg-teal-700 hover:bg-teal-800 text-white"
            onClick={() => {
              toast.success("Template saved (PoC mode — not persisted)", {
                description: `${template.archetypeName} · ${template.tier} template saved.`,
              });
              onClose();
            }}
          >
            Save Template
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

export default function ReportsPage() {
  const [editingTemplate, setEditingTemplate] = useState<ReportTemplate | null>(null);
  const [archetypeFilter, setArchetypeFilter] = useState<string>("all");

  const filteredTemplates =
    archetypeFilter === "all"
      ? REPORT_TEMPLATES
      : REPORT_TEMPLATES.filter((t) => t.archetypeId === archetypeFilter);

  return (
    <div className="space-y-6 p-6">
      {/* Header */}
      <div>
        <h1 className="text-2xl font-bold text-gray-900">Report Management</h1>
        <p className="text-sm text-gray-500">
          {REPORT_TEMPLATES.length} report templates across {ARCHETYPES.length} archetypes × 3 tiers
        </p>
      </div>

      <Tabs defaultValue="templates">
        <TabsList className="border-b border-gray-200 bg-transparent p-0 h-auto rounded-none gap-0">
          {["templates", "generated"].map((tab) => (
            <TabsTrigger
              key={tab}
              value={tab}
              className="rounded-none border-b-2 border-transparent px-4 py-2 text-sm font-medium capitalize text-gray-500 data-[state=active]:border-teal-600 data-[state=active]:text-teal-700 data-[state=active]:shadow-none"
            >
              {tab === "templates" ? `Templates (${REPORT_TEMPLATES.length})` : `Generated Reports (${DEMO_REPORTS.length})`}
            </TabsTrigger>
          ))}
        </TabsList>

        {/* Templates Tab */}
        <TabsContent value="templates" className="mt-6 space-y-4">
          {/* Filter */}
          <div className="flex flex-wrap gap-2">
            <Button
              variant={archetypeFilter === "all" ? "default" : "outline"}
              size="sm"
              className={`text-xs ${archetypeFilter === "all" ? "bg-teal-700 hover:bg-teal-800 text-white" : ""}`}
              onClick={() => setArchetypeFilter("all")}
            >
              All Archetypes
            </Button>
            {ARCHETYPES.map((a) => (
              <Button
                key={a.id}
                variant={archetypeFilter === a.id ? "default" : "outline"}
                size="sm"
                className="text-xs"
                style={archetypeFilter === a.id ? { backgroundColor: a.color, color: "white", borderColor: a.color } : {}}
                onClick={() => setArchetypeFilter(a.id)}
              >
                {a.name.replace("The ", "")}
              </Button>
            ))}
          </div>

          <Card>
            <CardContent className="p-0">
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b border-gray-100 bg-gray-50/50">
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">Archetype</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">Tier</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">Sections</th>
                    <th className="px-4 py-3 text-right text-xs font-medium text-gray-500">Action</th>
                  </tr>
                </thead>
                <tbody>
                  {filteredTemplates.map((template) => (
                    <tr
                      key={`${template.archetypeId}-${template.tier}`}
                      className="border-b border-gray-50 hover:bg-gray-50/60 transition-colors"
                    >
                      <td className="px-4 py-3">
                        <div className="flex items-center gap-2">
                          <span className="h-3 w-3 rounded-full shrink-0" style={{ backgroundColor: template.archetypeColor }} />
                          <span className="text-sm text-gray-700">{template.archetypeName}</span>
                        </div>
                      </td>
                      <td className="px-4 py-3">
                        <span className={`inline-flex rounded-full border px-2 py-0.5 text-[10px] font-medium capitalize ${TIER_STYLES[template.tier]}`}>
                          {template.tier}
                        </span>
                      </td>
                      <td className="px-4 py-3">
                        <div className="flex flex-wrap gap-1">
                          {["Profile", "Snapshot", "Nutrition"].map((s) => (
                            <span key={s} className="rounded border border-gray-200 bg-gray-50 px-1.5 py-0.5 text-[10px] text-gray-500">{s}</span>
                          ))}
                          {template.tier !== "starter" && (
                            <span className="rounded border border-amber-200 bg-amber-50 px-1.5 py-0.5 text-[10px] text-amber-700">GLP-1</span>
                          )}
                          {template.tier === "professional" && (
                            <span className="rounded border border-violet-200 bg-violet-50 px-1.5 py-0.5 text-[10px] text-violet-700">Action Plan</span>
                          )}
                        </div>
                      </td>
                      <td className="px-4 py-3 text-right">
                        <Button
                          variant="outline"
                          size="sm"
                          className="gap-1.5 text-xs"
                          onClick={() => setEditingTemplate(template)}
                        >
                          <Edit2 className="h-3.5 w-3.5" />
                          Edit Template
                        </Button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Generated Reports Tab */}
        <TabsContent value="generated" className="mt-6">
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-sm font-semibold">Generated Reports ({DEMO_REPORTS.length})</CardTitle>
            </CardHeader>
            <CardContent className="p-0">
              {DEMO_REPORTS.length === 0 ? (
                <div className="flex flex-col items-center justify-center py-12 text-center">
                  <FileText className="h-10 w-10 text-gray-300 mb-3" />
                  <p className="text-sm text-gray-500">No reports generated yet</p>
                </div>
              ) : (
                <table className="w-full text-sm">
                  <thead>
                    <tr className="border-b border-gray-100 bg-gray-50/50">
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">User</th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">Archetype</th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">Tier</th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">Generated</th>
                      <th className="px-4 py-3 text-right text-xs font-medium text-gray-500">Actions</th>
                    </tr>
                  </thead>
                  <tbody>
                    {DEMO_REPORTS.map((report) => {
                      const archetype = ARCHETYPES.find((a) => a.id === report.archetypeId);
                      return (
                        <tr key={report.id} className="border-b border-gray-50 hover:bg-gray-50/60">
                          <td className="px-4 py-3">
                            <p className="font-medium text-gray-800">{report.userName}</p>
                            <p className="text-xs text-gray-400">{report.userEmail}</p>
                          </td>
                          <td className="px-4 py-3">
                            {archetype ? (
                              <div className="flex items-center gap-2">
                                <span className="h-2.5 w-2.5 rounded-full" style={{ backgroundColor: archetype.color }} />
                                <span className="text-xs">{archetype.name.replace("The ", "")}</span>
                              </div>
                            ) : <span className="text-xs text-gray-400">—</span>}
                          </td>
                          <td className="px-4 py-3">
                            <span className={`inline-flex rounded-full border px-2 py-0.5 text-[10px] font-medium capitalize ${TIER_STYLES[(report.tier as Tier)] ?? ""}`}>
                              {report.tier}
                            </span>
                          </td>
                          <td className="px-4 py-3 text-xs text-gray-500">
                            {new Date(report.generatedAt).toLocaleDateString("en-GB", { day: "numeric", month: "short", year: "2-digit" })}
                          </td>
                          <td className="px-4 py-3 text-right">
                            <div className="flex justify-end gap-2">
                              <Button
                                variant="outline"
                                size="sm"
                                className="text-xs gap-1"
                                onClick={() => toast.info("In PoC mode — report viewer navigation simulated")}
                              >
                                View
                              </Button>
                              <Button
                                variant="outline"
                                size="sm"
                                className="text-xs gap-1"
                                onClick={() => toast.info("Report regeneration queued (PoC)")}
                              >
                                <RefreshCw className="h-3 w-3" />
                                Regenerate
                              </Button>
                            </div>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              )}
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>

      {editingTemplate && (
        <EditTemplateDialog
          template={editingTemplate}
          open={!!editingTemplate}
          onClose={() => setEditingTemplate(null)}
        />
      )}
    </div>
  );
}
