"use client";
import { useEffect, useState } from "react";
import { Heart, Pencil, Trash2, Plus } from "lucide-react";
import { useMasterDataStore } from "@/app/store/masterDataStore";
import { Symptom } from "@/app/types/masterData";
import PageHeader from "@/components/modals/ui/PageHeader";
import { useSymptomStore } from "@/app/store/symptomStore";
import {
  AddSymptomPayload,
  UpdateSymptomPayload,
} from "@/app/types/medicalData";
import ConfirmDeleteModal from "@/components/modals/ui/ConfirmDeleteModal";

import { X, Info, Printer } from "lucide-react";

function SymptomModal({
  open,
  onClose,
  onSubmit,
  loading,
  initialData,
}: {
  open: boolean;
  onClose: () => void;
  onSubmit: (data: any) => void;
  loading: boolean;
  initialData?: Symptom | null;
}) {
  const [form, setForm] = useState({
    drLang: "",
    ptLang: "",
  });

  useEffect(() => {
    if (open) {
      setForm({
        drLang: initialData?.drLang || "",
        ptLang: initialData?.ptLang || "",
      });
    }
  }, [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-[600px] rounded-3xl shadow-2xl">
        <div className="flex items-center justify-between px-7 py-5 border-b border-[#f3f4f6]">
          <p className="text-lg font-semibold text-[#d4537e]">
            {initialData ? "Edit Symptom" : "Add Symptom"}
          </p>

          <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-7 flex flex-col gap-6">
          {/* Info Box */}
          <div className="flex gap-3 bg-[#f7f7f8] rounded-2xl p-4">
            <Info size={18} className="text-[#9ca3af] mt-1 flex-shrink-0" />
            <p className="text-sm text-[#6b7280] leading-6">
              The doctor language appears on your screen; the patient language
              prints on the prescription.
            </p>
          </div>

          {/* Doctor Language */}
          <div>
            <label className="block text-sm font-medium text-[#374151] mb-2">
              Doctor Language
            </label>

            <input
              type="text"
              placeholder="i.e. Chest Pain"
              value={form.drLang}
              onChange={(e) =>
                setForm((prev) => ({
                  ...prev,
                  drLang: 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"
            />

            <p className="text-xs text-[#9ca3af] mt-2">
              Used in your app UI and symptom search
            </p>
          </div>

          {/* Patient Language */}
          <div>
            <label className="block text-sm font-medium text-[#374151] mb-2">
              Prescription (Patient) Language
            </label>

            <div className="relative">
              <Printer
                size={22}
                className="absolute left-4 top-1/2 -translate-y-1/2 text-[#d4537e]"
              />

              <input
                type="text"
                placeholder="i.e. છાતીમાં દુખાવો"
                value={form.ptLang}
                onChange={(e) =>
                  setForm((prev) => ({
                    ...prev,
                    ptLang: e.target.value,
                  }))
                }
                className="w-full bg-[#f7f7f8] rounded-xl border-none outline-none pl-14 pr-4 py-4 text-base text-[#111111] placeholder:text-[#9ca3af]"
              />
            </div>

            <p className="text-xs text-[#9ca3af] mt-2">
              Printed on the patient's prescription
            </p>
          </div>
        </div>

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

export default function SavedSymptomsPage({
  onClose,
}: {
  onClose: () => void;
}) {
  const { masterData, fetchMasterData, loading } = useMasterDataStore();
  const {
    addSymptom,
    updateSymptom,
    removeSymptom,
    loading: actionLoading,
  } = useSymptomStore();

  const [addOpen, setAddOpen] = useState(false);
  const [editSymptom, setEditSymptom] = useState<Symptom | null>(null);
  const [deleteSymptom, setDeleteSymptom] = useState<Symptom | null>(null);

  useEffect(() => {
    if (!masterData) fetchMasterData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const symptoms: Symptom[] = masterData?.symptoms || [];
  const handleAddSymptom = async (payload: AddSymptomPayload) => {
    const success = await addSymptom(payload);

    if (success) {
      setAddOpen(false);
    }
  };
  const handleUpdateSymptom = async (payload: UpdateSymptomPayload) => {
    const success = await updateSymptom(payload);

    if (success) {
      setEditSymptom(null);
    }
  };
  const handleDeleteSymptom = async () => {
    if (!deleteSymptom) return;

    const success = await removeSymptom(deleteSymptom.id);

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

  if (loading && !masterData) {
    return (
      <div className="bg-[#f7f7f8]">
        <PageHeader
          icon={<Heart size={20} />}
          title="Saved symptoms"
          subtitle="View, edit, or delete previously saved symptoms"

        />
        <main className="max-w-[680px] mx-auto p-7">
          <p className="text-sm text-[#9ca3af] text-center py-10">Loading...</p>
        </main>
      </div>
    );
  }

  return (
    <div className="bg-[#f7f7f8]">
      <PageHeader
        icon={<Heart size={20} />}
        title="Saved symptoms"
        subtitle="View, edit, or delete previously saved symptoms"
        onClose={onClose}

      />

      <div className="min-h-[calc(100vh-140px)] flex flex-col px-7 pt-7 pb-7 max-w-[680px] mx-auto">
        <div className="flex-1">
          {symptoms.length === 0 ? (
            <p className="text-sm text-[#9ca3af] text-center py-10">
              No symptoms saved yet
            </p>
          ) : (
            <div className="flex flex-col gap-3">
              {symptoms.map((s) => (
                <div
                  key={s.id}
                  className="flex items-center justify-between gap-4 bg-white border border-[#e5e7eb] rounded-2xl px-5 py-4"
                >
                  <div className="min-w-0">
                    <p className="text-base font-semibold text-[#111111]">
                      {s.drLang}
                    </p>
                    {s.ptLang && s.ptLang == s.drLang && (
                      <p className="text-sm text-[#9ca3af] mt-0.5">
                        {s.ptLang}
                      </p>
                    )}
                  </div>
                  <div className="flex items-center gap-2 flex-shrink-0">
                    <button
                      className="w-9 h-9 rounded-lg flex items-center justify-center text-[#d4537e] bg-[#fceef3] hover:bg-[#f8d9e4] border-none cursor-pointer transition-colors"
                      onClick={() => setEditSymptom(s)} // TODO: wire edit form
                    >
                      <Pencil size={16} />
                    </button>
                    <button
                      className="w-9 h-9 rounded-lg flex items-center justify-center text-[#ef4444] bg-[#fff1f1] hover:bg-[#ffe1e1] border-none cursor-pointer transition-colors"
                      onClick={() => setDeleteSymptom(s)} // TODO: wire delete API
                    >
                      <Trash2 size={16} />
                    </button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
        <button
          className="w-full flex items-center gap-4 bg-white border border-[#e5e7eb] rounded-2xl px-6 py-4 mt-6 cursor-pointer hover:bg-[#f7f7f8] transition-colors"
          onClick={() => setAddOpen(true)} // TODO: link to add-symptom page
        >
          <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 symptom
            </p>
            <p className="text-sm text-[#9ca3af]">
              Not listed above? Add your own
            </p>
          </div>
        </button>
      </div>
      <SymptomModal
        open={addOpen}
        onClose={() => setAddOpen(false)}
        onSubmit={handleAddSymptom}
        loading={actionLoading}
      />

      <SymptomModal
        open={!!editSymptom}
        initialData={editSymptom}
        onClose={() => setEditSymptom(null)}
        onSubmit={handleUpdateSymptom}
        loading={actionLoading}
      />
      <ConfirmDeleteModal
        open={!!deleteSymptom}
        title="Delete Symptom?"
        description={`Are you sure you want to remove ${deleteSymptom?.drLang}?`}
        onCancel={() => setDeleteSymptom(null)}
        onConfirm={handleDeleteSymptom}
        loading={actionLoading}
      />
    </div>
  );
}
