"use client";
import { useEffect, useState } from "react";
import {
  ScanText,
  CheckCircle2,
  XCircle,
  ClipboardList,
  Pencil,
  Trash2,
  Plus,
  FileSymlink,
  X,
  Check,
} from "lucide-react";
import { useMasterDataStore } from "@/app/store/masterDataStore";
import { Instruction } from "@/app/types/masterData";
import PageHeader from "@/components/modals/ui/PageHeader";
import { useInstructionStore } from "@/app/store/instructionStore";
import {
  AddInstructionPayload,
  UpdateInstructionPayload,
} from "@/app/types/medicalData";
import ConfirmDeleteModal from "@/components/modals/ui/ConfirmDeleteModal";

interface ImportInstruction {
  language: string;
  symptom_name: string;
  should_eat: string;
  should_not_eat: string;
  extra: string;
}

/* -------------------------------------------------------------------- */
/*  The API sends short language codes ("gj", "en", "hi"...). We only    */
/*  ever show a human-readable full name in the UI — the raw code is     */
/*  still what we filter/compare against internally.                    */
/* -------------------------------------------------------------------- */

const LANGUAGE_LABELS: Record<string, string> = {
  gj: "Gujarati",
  guj: "Gujarati",
  gujarati: "Gujarati",
  en: "English",
  eng: "English",
  english: "English",
  hi: "Hindi",
  hin: "Hindi",
  hindi: "Hindi",
};

function languageLabel(code: string): string {
  const key = code?.toLowerCase?.() ?? "";
  return LANGUAGE_LABELS[key] ?? code;
}

/* -------------------------------------------------------------------- */
/*  Empty state — shown when there are no saved instructions at all.     */
/*  Icon mirrors the page header icon so the two feel like one system.  */
/* -------------------------------------------------------------------- */

function EmptyInstructionsState() {
  return (
    <div className="flex flex-col items-center justify-center gap-4 text-center px-6">
      <span className="w-28 h-28 rounded-[28px] bg-[#fceef3] text-[#d4537e] flex items-center justify-center">
        <ScanText size={48} strokeWidth={1.6} />
      </span>
      <div>
        <p className="text-xl font-semibold text-[#111111]">
          No instructions saved yet.
        </p>
        <p className="text-base text-[#9ca3af] mt-1.5">
          Tap below to import or add your own.
        </p>
      </div>
    </div>
  );
}

function InstructionModal({
  open,
  onClose,
  onSubmit,
  loading,
  initialData,
}: {
  open: boolean;
  onClose: () => void;
  onSubmit: (data: any) => void;
  loading: boolean;
  initialData?: Instruction | null;
}) {
  const [form, setForm] = useState({
    symptomName: "",
    shouldDo: "",
    shouldNotDo: "",
    extra: "",
  });

  useEffect(() => {
    if (open) {
      setForm({
        symptomName: initialData?.symptomName || "",
        shouldDo: initialData?.shouldDo || "",
        shouldNotDo: initialData?.shouldNotDo || "",
        extra: initialData?.extra || "",
      });
    }
  }, [open, initialData]);

  if (!open) return null;

  return (
    <div className="fixed inset-0 z-[100] flex items-center justify-center p-4">
      <div className="absolute inset-0 bg-black/50" onClick={onClose} />

      <div className="relative bg-white w-full max-w-[700px] rounded-3xl shadow-2xl">
        <div className="flex items-center justify-between px-6 py-5 border-b border-[#f3f4f6]">
          <h2 className="text-lg font-semibold text-[#d4537e]">
            {initialData ? "Edit Instruction" : "Add Instruction"}
          </h2>

          <button
            onClick={onClose}
            className="w-9 h-9 rounded-lg flex items-center justify-center text-[#9ca3af] hover:bg-[#f7f7f8] border-none cursor-pointer"
          >
            <X size={20} />
          </button>
        </div>

        <div className="p-6 flex flex-col gap-5">
          <div>
            <label className="block text-sm font-medium text-[#374151] mb-2">
              Symptom Name in Dr. Language
            </label>
            <input
              placeholder="i.e. Chest Pain"
              value={form.symptomName}
              onChange={(e) =>
                setForm({
                  ...form,
                  symptomName: e.target.value,
                })
              }
              disabled={!!initialData}
              className="w-full bg-[#f7f7f8] rounded-xl border-none outline-none px-4 py-4 text-base text-[#111111] placeholder:text-[#9ca3af] disabled:opacity-50 disabled:cursor-not-allowed"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-[#374151] mb-2">
              What should Do in Pt Language
            </label>
            <textarea
              rows={3}
              placeholder="i.e. छाती में दर्द"
              value={form.shouldDo}
              onChange={(e) =>
                setForm({
                  ...form,
                  shouldDo: e.target.value,
                })
              }
              className="w-full bg-[#f7f7f8] rounded-xl border-none outline-none px-4 py-4 text-base text-[#111111] placeholder:text-[#9ca3af]"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-[#374151] mb-2">
              What should not Do in Pt Language
            </label>
            <textarea
              placeholder="i.e. छाती में दर्द"
              rows={3}
              value={form.shouldNotDo}
              onChange={(e) =>
                setForm({
                  ...form,
                  shouldNotDo: e.target.value,
                })
              }
              className="w-full bg-[#f7f7f8] rounded-xl border-none outline-none px-4 py-4 text-base text-[#111111] placeholder:text-[#9ca3af]"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-[#374151] mb-2">
              Extra instruction in Pt Language
            </label>
            <textarea
              placeholder="i.e. छाती में दर्द"
              rows={3}
              value={form.extra}
              onChange={(e) =>
                setForm({
                  ...form,
                  extra: e.target.value,
                })
              }
              className="w-full bg-[#f7f7f8] rounded-xl border-none outline-none px-4 py-4 text-base text-[#111111] placeholder:text-[#9ca3af]"
            />
          </div>
        </div>

        <div className="px-6 pb-6">
          <button
            disabled={!form.symptomName.trim() || loading}
            onClick={() =>
              initialData
                ? onSubmit({
                    id: initialData.id,
                    ...form,
                  })
                : onSubmit(form)
            }
            className="w-full bg-[#d4537e] hover:bg-[#993556] text-white py-4 rounded-2xl font-semibold disabled:opacity-50"
          >
            {loading
              ? "Saving..."
              : initialData
                ? "Update Instruction"
                : "Save"}
          </button>
        </div>
      </div>
    </div>
  );
}

/* -------------------------------------------------------------------- */
/*  Import modal — language filter chips + per-item language badge +     */
/*  a custom (non-native) checkbox, matching the reference design.       */
/* -------------------------------------------------------------------- */

function ImportInstructionsModal({
  open,
  onClose,
  instructions,
  selected,
  setSelected,
  onImport,
}: {
  open: boolean;
  onClose: () => void;
  instructions: ImportInstruction[];
  selected: string[];
  setSelected: React.Dispatch<React.SetStateAction<string[]>>;
  onImport: () => void;
}) {
  const [langFilter, setLangFilter] = useState("All");

  useEffect(() => {
    if (open) setLangFilter("All");
  }, [open]);

  if (!open) return null;

  const languages = Array.from(
    new Set(instructions.map((i) => i.language).filter(Boolean)),
  );

  const visible =
    langFilter === "All"
      ? instructions
      : instructions.filter((i) => i.language === langFilter);

  const filterPill = (active: boolean) =>
    `px-5 py-2.5 rounded-full text-sm font-medium cursor-pointer border-none transition-colors whitespace-nowrap ${
      active
        ? "bg-[#d4537e] text-white"
        : "bg-[#f7f7f8] text-[#374151] hover:bg-[#fceef3] hover:text-[#d4537e]"
    }`;

  return (
    <div className="fixed inset-0 z-[100] flex items-center justify-center">
      <div className="absolute inset-0 bg-black/50" onClick={onClose} />

      <div className="relative bg-white w-full max-w-[800px] max-h-[90vh] overflow-y-auto rounded-3xl">
<div className="flex items-start justify-between p-6 border border-[#e5e7eb] sticky top-0 bg-white z-10">        
    <div>
            <h2 className="text-lg font-semibold text-[#d4537e]">
              Import Instructions
            </h2>

            <p className="text-sm text-gray-500 mt-1">
              Select instructions to import. Already saved ones are excluded.
            </p>
          </div>

          <button
            onClick={onClose}
            className="w-9 h-9 rounded-lg flex items-center justify-center text-[#9ca3af] hover:bg-[#f7f7f8] border-none cursor-pointer flex-shrink-0"
          >
            <X size={20} />
          </button>
        </div>

        {/* Language filter chips */}
        <div className="flex gap-2 px-6 pt-5 flex-wrap">
          <button
            onClick={() => setLangFilter("All")}
            className={filterPill(langFilter === "All")}
          >
            All
          </button>
          {languages.map((lang) => (
            <button
              key={lang}
              onClick={() => setLangFilter(lang)}
              className={filterPill(langFilter === lang)}
            >
              {languageLabel(lang)}
            </button>
          ))}
        </div>

        <div className="p-6 flex flex-col gap-5">
          {visible.map((item, index) => {
            const checked = selected.includes(item.symptom_name);
            const badge = item.language
              ? item.language.slice(0, 2).toUpperCase()
              : "";
            return (
              <div
                key={index}
                className="border border-[#e5e7eb] rounded-2xl p-4 flex gap-4 relative"
              >
                {/* Custom checkbox */}
                <button
                  type="button"
                  onClick={() => {
                    if (checked) {
                      setSelected((prev) =>
                        prev.filter((name) => name !== item.symptom_name),
                      );
                    } else {
                      setSelected((prev) => [...prev, item.symptom_name]);
                    }
                  }}
                  className={`mt-1 w-5 h-5 rounded-md border-2 flex items-center justify-center flex-shrink-0 cursor-pointer transition-colors ${
                    checked
                      ? "bg-[#d4537e] border-[#d4537e]"
                      : "bg-white border-[#d4537e]"
                  }`}
                >
                  {checked && (
                    <Check size={12} strokeWidth={3.5} className="text-white" />
                  )}
                </button>

                <div className="flex-1 pr-14">
                  <p className="font-medium text-[#111111]">
                    {item.symptom_name}
                  </p>
                  {item.should_eat && (
                    <p className="text-sm text-[#374151] mt-1">
                      ✅ {item.should_eat}
                    </p>
                  )}
                  {item.should_not_eat && (
                    <p className="text-sm text-[#374151] mt-1">
                      ❌ {item.should_not_eat}
                    </p>
                  )}
                  {item.extra && (
                    <p className="text-sm text-[#374151] mt-1">
                      📋 {item.extra}
                    </p>
                  )}
                </div>

                {/* Language badge */}
                {badge && (
                  <span className="absolute top-4 right-4 w-9 h-9 rounded-full bg-[#eaf2ff] text-[#2563eb] text-xs font-semibold flex items-center justify-center">
                    {badge}
                  </span>
                )}
              </div>
            );
          })}

          {visible.length === 0 && (
            <p className="text-sm text-[#9ca3af] text-center py-8">
              No instructions in this language.
            </p>
          )}
        </div>

        <div className="sticky bottom-0 bg-white border border-[#e5e7eb] p-4 flex items-center justify-between">
          <p className="text-sm text-gray-500 mt-1">
            {selected.length} item(s) selected
          </p>
          <button
            disabled={!selected.length}
            onClick={onImport}
            className="bg-[#d4537e] text-white px-8 py-3 rounded-xl disabled:opacity-50"
          >
            Import
          </button>
        </div>
      </div>
    </div>
  );
}

export default function InstructionsPage({
  onClose,
}: {
  onClose: () => void;
}) {  const { masterData, fetchMasterData, loading } = useMasterDataStore();
  const {
    addInstruction,
    updateInstruction,
    removeInstruction,
    loading: actionLoading,
  } = useInstructionStore();

  const [importOpen, setImportOpen] = useState(false);

  const [instructionsData, setInstructionsData] = useState<ImportInstruction[]>(
    [],
  );
  const [selected, setSelected] = useState<string[]>([]);
  const handleImport = async () => {
    const selectedItems = instructionsData.filter((item) =>
      selected.includes(item.symptom_name),
    );

    for (const item of selectedItems) {
      await addInstruction({
        symptomName: item.symptom_name,
        shouldDo: item.should_eat,
        shouldNotDo: item.should_not_eat,
        extra: item.extra,
      });
    }
    setSelected([]);
    setImportOpen(false);
  };

  const [addOpen, setAddOpen] = useState(false);
  const [editInstruction, setEditInstruction] = useState<Instruction | null>(
    null,
  );

  const [deleteInstruction, setDeleteInstruction] =
    useState<Instruction | null>(null);

  const handleAddInstruction = async (payload: AddInstructionPayload) => {
    const success = await addInstruction(payload);

    if (success) {
      setAddOpen(false);
    }
  };

  const handleUpdateInstruction = async (payload: UpdateInstructionPayload) => {
    const success = await updateInstruction(payload);

    if (success) {
      setEditInstruction(null);
    }
  };

  const handleDeleteInstruction = async () => {
    if (!deleteInstruction) return;

    const success = await removeInstruction(deleteInstruction.id);

    if (success) {
      setDeleteInstruction(null);
    }
  };

  useEffect(() => {
    if (!masterData) fetchMasterData();
  }, []);

  const instructions: Instruction[] = masterData?.instructions || [];

  return (
    // h-full (not min-h-screen) so this fits exactly inside whatever
    // fixed-height panel/drawer renders it — only the middle list/empty
    // area scrolls; header and the bottom action buttons stay pinned.
    <div className="h-full bg-[#f5f5f7] flex flex-col overflow-hidden">
      <PageHeader
        icon={<ScanText size={20} />}
        title="Instructions/Advices"
        subtitle="Save, import, and manage your instructions easily."
        onClose={onClose}
      />

      <div className="flex-1 flex flex-col w-full max-w-[760px] mx-auto min-h-0">
        <div className="flex-1 min-h-0 overflow-y-auto px-7">
          {loading && !masterData ? (
            <p className="text-sm text-[#9ca3af] text-center py-10">
              Loading...
            </p>
          ) : instructions.length === 0 ? (
            <div className="h-full flex items-center justify-center">
              <EmptyInstructionsState />
            </div>
          ) : (
            <div className="flex flex-col gap-4 py-7">
              {instructions.map((ins) => (
                <div
                  key={ins.id}
                  className="bg-white border border-[#e5e7eb] rounded-2xl p-6"
                >
                  <div className="flex items-center justify-between gap-3 mb-4">
                    <p className="text-base font-semibold text-[#111111]">
                      {ins.symptomName}
                    </p>
                    <div className="flex items-center gap-2 flex-shrink-0">
                      <button
                        className="w-8 h-8 rounded-lg flex items-center justify-center text-[#d4537e] bg-[#fceef3] hover:bg-[#f8d9e4] border-none cursor-pointer transition-colors"
                        onClick={() => setEditInstruction(ins)}
                      >
                        <Pencil size={14} />
                      </button>
                      <button
                        className="w-8 h-8 rounded-lg flex items-center justify-center text-[#ef4444] bg-[#fff1f1] hover:bg-[#ffe1e1] border-none cursor-pointer transition-colors"
                        onClick={() => setDeleteInstruction(ins)}
                      >
                        <Trash2 size={14} />
                      </button>
                    </div>
                  </div>

                  {ins.shouldDo && (
                    <div className="flex items-start gap-2.5 mb-2.5">
                      <CheckCircle2
                        size={16}
                        className="text-[#16a34a] mt-0.5 flex-shrink-0"
                      />
                      <p className="text-sm text-[#374151]">{ins.shouldDo}</p>
                    </div>
                  )}
                  {ins.shouldNotDo && (
                    <div className="flex items-start gap-2.5 mb-2.5">
                      <XCircle
                        size={16}
                        className="text-[#ef4444] mt-0.5 flex-shrink-0"
                      />
                      <p className="text-sm text-[#374151]">
                        {ins.shouldNotDo}
                      </p>
                    </div>
                  )}
                  {ins.extra && (
                    <div className="flex items-start gap-2.5">
                      <ClipboardList
                        size={16}
                        className="text-[#4f46e5] mt-0.5 flex-shrink-0"
                      />
                      <p className="text-sm text-[#374151]">{ins.extra}</p>
                    </div>
                  )}
                </div>
              ))}
            </div>
          )}
        </div>

        <div className="flex flex-col gap-3 px-7 py-5 flex-shrink-0 bg-[#f5f5f7]">
          <button
            className="w-full flex items-center gap-4 bg-[#e8f8ee] border border-transparent rounded-2xl px-6 py-4 cursor-pointer hover:opacity-90 transition-opacity"
            onClick={async () => {
              const res = await fetch("/data/instructions.json");
              const data = await res.json();
              setInstructionsData(data.instructions);
              setImportOpen(true);
            }}
          >
            <span className="w-10 h-10 rounded-xl bg-white text-[#16a34a] flex items-center justify-center flex-shrink-0">
              <FileSymlink size={20} />
            </span>
            <div className="text-left">
              <p className="text-base font-medium text-[#111111]">
                Import ready-made instructions
              </p>
              <p className="text-sm text-[#4b5563]">
                Add common instructions in one tap
              </p>
            </div>
          </button>

          <button
            className="w-full flex items-center gap-4 bg-white border border-[#e5e7eb] rounded-2xl px-6 py-4 cursor-pointer hover:bg-[#f7f7f8] transition-colors"
            onClick={() => setAddOpen(true)}
          >
            <span className="w-10 h-10 rounded-xl bg-[#fceef3] text-[#d4537e] flex items-center justify-center flex-shrink-0">
              <Plus size={20} />
            </span>
            <div className="text-left">
              <p className="text-base font-medium text-[#111111]">
                Add new instruction
              </p>
              <p className="text-sm text-[#9ca3af]">
                Not listed above? Add your own
              </p>
            </div>
          </button>
        </div>
      </div>
      <ImportInstructionsModal
        open={importOpen}
        onClose={() => setImportOpen(false)}
        instructions={instructionsData}
        selected={selected}
        setSelected={setSelected}
        onImport={handleImport}
      />
      <InstructionModal
        open={addOpen}
        onClose={() => setAddOpen(false)}
        onSubmit={handleAddInstruction}
        loading={actionLoading}
      />

      <InstructionModal
        open={!!editInstruction}
        initialData={editInstruction}
        onClose={() => setEditInstruction(null)}
        onSubmit={handleUpdateInstruction}
        loading={actionLoading}
      />

      <ConfirmDeleteModal
        open={!!deleteInstruction}
        title="Delete Instruction?"
        description={`Are you sure you want to remove ${deleteInstruction?.symptomName}?`}
        onCancel={() => setDeleteInstruction(null)}
        onConfirm={handleDeleteInstruction}
        loading={actionLoading}
      />
    </div>
  );
}