"use client";

import { BookOpen, ChevronDown, ChevronUp, Edit2, Flag, Plus, ToggleLeft } 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 } 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 { Textarea } from "@/components/ui/textarea";
import { QUESTIONNAIRE_SECTIONS } from "@/data/questionnaire";
import type { Question } from "@/types/novalife";

const TYPE_COLORS: Record<string, string> = {
  single: "bg-blue-50 text-blue-700 border-blue-200",
  multi: "bg-violet-50 text-violet-700 border-violet-200",
  scale: "bg-amber-50 text-amber-700 border-amber-200",
  number: "bg-teal-50 text-teal-700 border-teal-200",
  text: "bg-gray-50 text-gray-600 border-gray-200",
  "optional-number": "bg-emerald-50 text-emerald-700 border-emerald-200",
};

function hasGlp1Flag(q: Question): boolean {
  return q.options?.some((o) => o.glp1Flag) ?? false;
}

function EditQuestionDialog({ question, open, onClose }: { question: Question; open: boolean; onClose: () => void }) {
  return (
    <Dialog open={open} onOpenChange={onClose}>
      <DialogContent className="max-w-lg">
        <DialogHeader>
          <DialogTitle>Edit Question</DialogTitle>
        </DialogHeader>
        <div className="space-y-4">
          <div>
            <Label className="text-xs text-gray-500">Question ID</Label>
            <Input value={question.id} readOnly className="mt-1 text-xs bg-gray-50" />
          </div>
          <div>
            <Label className="text-xs">Question Text</Label>
            <Textarea
              defaultValue={question.text}
              className="mt-1 text-sm resize-none"
              rows={3}
            />
          </div>
          {question.subtext && (
            <div>
              <Label className="text-xs">Sub-text</Label>
              <Input defaultValue={question.subtext} className="mt-1 text-sm" />
            </div>
          )}
          <div className="flex items-center gap-3">
            <div className="flex-1">
              <Label className="text-xs">Type</Label>
              <Input value={question.type} readOnly className="mt-1 text-xs bg-gray-50" />
            </div>
            <div className="flex items-center gap-2 mt-5">
              <span className="text-xs text-gray-500">Required</span>
              <Badge
                className={question.isRequired ? "bg-emerald-50 text-emerald-700 border-emerald-200" : "bg-gray-50 text-gray-500 border-gray-200"}
              >
                {question.isRequired ? "Yes" : "No"}
              </Badge>
            </div>
          </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("Changes not persisted in PoC mode", { description: `Question "${question.id}" would be updated in production.` });
              onClose();
            }}
          >
            Save Changes
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

export default function QuestionnairePage() {
  const [expandedSections, setExpandedSections] = useState<number[]>([]);
  const [editingQuestion, setEditingQuestion] = useState<Question | null>(null);

  const toggleSection = (idx: number) => {
    setExpandedSections((prev) =>
      prev.includes(idx) ? prev.filter((i) => i !== idx) : [...prev, idx],
    );
  };

  const totalQuestions = QUESTIONNAIRE_SECTIONS.reduce((acc, s) => acc + s.questions.length, 0);
  const glp1Questions = QUESTIONNAIRE_SECTIONS.reduce(
    (acc, s) => acc + s.questions.filter(hasGlp1Flag).length, 0,
  );

  return (
    <div className="space-y-6 p-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Questionnaire Management</h1>
          <p className="text-sm text-gray-500">
            {QUESTIONNAIRE_SECTIONS.length} sections · {totalQuestions} questions · {glp1Questions} GLP-1 triggers
          </p>
        </div>
        <Button
          size="sm"
          variant="outline"
          className="gap-2"
          onClick={() => toast.info("In PoC mode — section creation not persisted")}
        >
          <Plus className="h-4 w-4" />
          Add Section
        </Button>
      </div>

      {/* Sections */}
      <div className="space-y-3">
        {QUESTIONNAIRE_SECTIONS.map((section) => {
          const isExpanded = expandedSections.includes(section.index);
          const sectionGlp1 = section.questions.filter(hasGlp1Flag).length;

          return (
            <Card key={section.index} className="overflow-hidden">
              {/* Section header */}
              <CardHeader
                className="cursor-pointer select-none p-4 hover:bg-gray-50 transition-colors"
                onClick={() => toggleSection(section.index)}
              >
                <div className="flex items-center gap-4">
                  <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-teal-50 text-sm font-bold text-teal-700">
                    {section.index + 1}
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2">
                      <h3 className="font-semibold text-gray-900 text-sm">{section.title}</h3>
                      {section.isOptional && (
                        <Badge className="bg-gray-100 text-gray-500 border-gray-200 text-[10px]">Optional</Badge>
                      )}
                      {sectionGlp1 > 0 && (
                        <Badge className="bg-amber-50 text-amber-700 border-amber-200 text-[10px] gap-1">
                          <Flag className="h-2.5 w-2.5" />
                          {sectionGlp1} GLP-1
                        </Badge>
                      )}
                    </div>
                    <p className="text-xs text-gray-400 truncate mt-0.5">{section.description}</p>
                  </div>
                  <div className="shrink-0 flex items-center gap-3">
                    <span className="text-xs text-gray-500 font-medium">{section.questions.length} questions</span>
                    <Button
                      variant="ghost"
                      size="sm"
                      className="gap-1 text-xs text-teal-700 hover:text-teal-800"
                      onClick={(e) => {
                        e.stopPropagation();
                        toast.info("In PoC mode — new question not persisted", { description: `Section: ${section.title}` });
                      }}
                    >
                      <Plus className="h-3.5 w-3.5" />
                      Add
                    </Button>
                    {isExpanded ? (
                      <ChevronUp className="h-4 w-4 text-gray-400" />
                    ) : (
                      <ChevronDown className="h-4 w-4 text-gray-400" />
                    )}
                  </div>
                </div>
              </CardHeader>

              {/* Questions */}
              {isExpanded && (
                <CardContent className="border-t border-gray-100 p-0">
                  {section.questions.map((q, qIdx) => {
                    const isGlp1 = hasGlp1Flag(q);
                    return (
                      <div
                        key={q.id}
                        className={`flex items-start gap-3 border-b border-gray-50 p-4 hover:bg-gray-50/50 transition-colors ${qIdx === section.questions.length - 1 ? "border-0" : ""}`}
                      >
                        <span className="mt-0.5 text-xs font-mono text-gray-300 w-5 shrink-0">{qIdx + 1}</span>
                        <div className="flex-1 min-w-0">
                          <div className="flex flex-wrap items-center gap-2 mb-1">
                            <span className={`inline-flex rounded-full border px-2 py-0.5 text-[10px] font-medium capitalize ${TYPE_COLORS[q.type] ?? ""}`}>
                              {q.type}
                            </span>
                            {!q.isRequired && (
                              <span className="inline-flex rounded-full border border-gray-200 bg-gray-50 px-2 py-0.5 text-[10px] font-medium text-gray-500">
                                Optional
                              </span>
                            )}
                            {isGlp1 && (
                              <span className="inline-flex items-center gap-1 rounded-full border border-amber-200 bg-amber-50 px-2 py-0.5 text-[10px] font-medium text-amber-700">
                                <Flag className="h-2.5 w-2.5" />
                                GLP-1 Trigger
                              </span>
                            )}
                            {q.unit && (
                              <span className="text-[10px] text-gray-400">Unit: {q.unit}</span>
                            )}
                          </div>
                          <p className="text-sm text-gray-700">{q.text}</p>
                          {q.subtext && <p className="text-xs text-gray-400 mt-0.5">{q.subtext}</p>}
                          {q.options && (
                            <div className="mt-2 flex flex-wrap gap-1">
                              {q.options.map((opt) => (
                                <span
                                  key={opt.id}
                                  className={`inline-flex rounded border px-1.5 py-0.5 text-[10px] text-gray-500 ${opt.glp1Flag ? "border-amber-300 bg-amber-50 text-amber-700" : "border-gray-200 bg-gray-50"}`}
                                >
                                  {opt.label}
                                  {opt.glp1Flag && <Flag className="ml-1 h-2.5 w-2.5 text-amber-600" />}
                                </span>
                              ))}
                            </div>
                          )}
                        </div>
                        <div className="shrink-0 flex gap-1.5">
                          <Button
                            variant="ghost"
                            size="icon"
                            className="h-7 w-7 text-gray-400 hover:text-teal-700"
                            title="Edit question"
                            onClick={() => setEditingQuestion(q)}
                          >
                            <Edit2 className="h-3.5 w-3.5" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="icon"
                            className="h-7 w-7 text-gray-400 hover:text-amber-700"
                            title="Toggle mandatory"
                            onClick={() => toast.info("In PoC mode — mandatory toggle simulated")}
                          >
                            <ToggleLeft className="h-3.5 w-3.5" />
                          </Button>
                        </div>
                      </div>
                    );
                  })}
                </CardContent>
              )}
            </Card>
          );
        })}
      </div>

      {/* Edit Dialog */}
      {editingQuestion && (
        <EditQuestionDialog
          question={editingQuestion}
          open={!!editingQuestion}
          onClose={() => setEditingQuestion(null)}
        />
      )}

      {/* Summary card */}
      <Card className="border-dashed border-gray-200 bg-gray-50/50">
        <CardContent className="flex items-center gap-4 p-4">
          <BookOpen className="h-5 w-5 text-gray-400 shrink-0" />
          <div>
            <p className="text-sm font-medium text-gray-700">Questionnaire Structure</p>
            <p className="text-xs text-gray-500 mt-0.5">
              {QUESTIONNAIRE_SECTIONS.length} sections · {totalQuestions} total questions ·
              {" "}{QUESTIONNAIRE_SECTIONS.filter(s => s.isOptional).length} optional sections ·
              {" "}{glp1Questions} questions with GLP-1 triggers
            </p>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
