"use client";
import { useRef, useState } from "react";
import { Field, TextArea, TextInput, Toast } from "../ui";
import { DoctorProfile } from "../_types";
import { saveDoctorProfile } from "../_api";
import { useHms } from "../layout";
import CommonTitle from "@/app/components/CommonTitle";

export default function SetupPage() {
  const { organizationId, userId, doctor, setDoctor } = useHms();
  const [form, setForm] = useState<DoctorProfile>(doctor);
  const [saved, setSaved] = useState("");
  const [saving, setSaving] = useState(false);
  const photoRef = useRef<HTMLInputElement>(null);
  const sigRef = useRef<HTMLInputElement>(null);
  const logoRef = useRef<HTMLInputElement>(null);

  const set = (k: keyof DoctorProfile) => (v: string) => setForm((p) => ({ ...p, [k]: v }));

  // Preview-only for now: picking a file swaps in an instant local preview;
  // wiring a real multipart upload to the ImageField is a follow-up.
  const onFile = (key: "photo" | "signature" | "logo") => (e: React.ChangeEvent<HTMLInputElement>) => {
    const f = e.target.files?.[0];
    if (!f) return;
    setForm((p) => ({ ...p, [key]: URL.createObjectURL(f) }));
  };

  const save = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    try {
      const updated = await saveDoctorProfile({ ...form, organization: organizationId, user: userId });
      setDoctor(updated);
      setSaved("Profile saved.");
      setTimeout(() => setSaved(""), 2500);
    } finally {
      setSaving(false);
    }
  };

  return (
    <>
      <CommonTitle
        title="Doctor Setup"
        description="Clinic letterhead info used on every printed prescription"
      />
      <div className="row">
        <div className="col-12 col-xl-8">
          <Toast message={saved} tone="success" />

          <div className="card">
            <form onSubmit={save} className="border rounded p-3">
              <div className="mb-3">
                <Field label="Hospital logo">
                  <div className="d-flex align-items-center gap-2">
                    <div
                      className="border rounded d-flex align-items-center justify-content-center overflow-hidden flex-shrink-0"
                      style={{ width: 64, height: 64 }}
                    >
                      {form.logo ? (
                        <img
                          src={form.logo}
                          alt=""
                          className="w-100 h-100"
                          style={{ objectFit: "contain" }}
                        />
                      ) : (
                        <span className="text-muted small">Logo</span>
                      )}
                    </div>
                    <button
                      type="button"
                      onClick={() => logoRef.current?.click()}
                      className="btn btn-outline-secondary btn-sm"
                    >
                      Upload logo
                    </button>
                    {form.logo && (
                      <button
                        type="button"
                        onClick={() => set("logo")("")}
                        className="btn btn-link btn-sm text-danger"
                      >
                        Remove
                      </button>
                    )}
                    <input
                      ref={logoRef}
                      type="file"
                      accept="image/*"
                      className="d-none"
                      onChange={onFile("logo")}
                    />
                  </div>
                </Field>
              </div>
              <div className="row g-3 mb-3">
                <div className="col-md-6">
                  <Field label="Your name">
                    <TextInput
                      value={form.name}
                      onChange={(e) => set("name")(e.target.value)}
                      required
                    />
                  </Field>
                </div>
                <div className="col-md-6">
                  <Field label="Clinic / hospital name">
                    <TextInput
                      value={form.clinic_name}
                      onChange={(e) => set("clinic_name")(e.target.value)}
                    />
                  </Field>
                </div>
              </div>
              <div className="row g-3 mb-3">
                <div className="col-md-6">
                  <Field label="Registration no.">
                    <TextInput
                      value={form.registration_no}
                      onChange={(e) => set("registration_no")(e.target.value)}
                    />
                  </Field>
                </div>
                <div className="col-md-6">
                  <Field label="Contact">
                    <TextInput
                      value={form.contact}
                      onChange={(e) => set("contact")(e.target.value)}
                    />
                  </Field>
                </div>
              </div>
              <div className="mb-3">
                <Field label="Specialization">
                  <TextArea
                    rows={2}
                    value={form.specialization}
                    onChange={(e) => set("specialization")(e.target.value)}
                  />
                </Field>
              </div>
              <div className="mb-3">
                <Field
                  label="Degree(s)"
                  hint="One per line — shown exactly as typed on the prescription."
                >
                  <TextArea
                    rows={2}
                    value={form.degree}
                    onChange={(e) => set("degree")(e.target.value)}
                  />
                </Field>
              </div>
              <div className="mb-3">
                <Field label="Clinic address">
                  <TextArea
                    rows={2}
                    value={form.clinic_address}
                    onChange={(e) => set("clinic_address")(e.target.value)}
                  />
                </Field>
              </div>
              <div className="row g-3 mb-3">
                <div className="col-md-6">
                  <Field label="Chamber days">
                    <TextInput
                      value={form.chamber_days}
                      onChange={(e) => set("chamber_days")(e.target.value)}
                      placeholder="Sat – Thu"
                    />
                  </Field>
                </div>
                <div className="col-md-6">
                  <Field label="Chamber hours">
                    <TextInput
                      value={form.chamber_hours}
                      onChange={(e) => set("chamber_hours")(e.target.value)}
                      placeholder="5:00 PM – 9:00 PM"
                    />
                  </Field>
                </div>
              </div>
              <div className="row g-3 mb-3">
                <div className="col-md-6">
                  <Field label="Photo">
                    <div className="d-flex align-items-center gap-2">
                      <div
                        className="rounded-circle border d-flex align-items-center justify-content-center overflow-hidden flex-shrink-0"
                        style={{ width: 48, height: 48 }}
                      >
                        {form.photo ? (
                          <img
                            src={form.photo}
                            alt=""
                            className="w-100 h-100"
                            style={{ objectFit: "cover" }}
                          />
                        ) : (
                          <span className="text-muted small">—</span>
                        )}
                      </div>
                      <button
                        type="button"
                        onClick={() => photoRef.current?.click()}
                        className="btn btn-outline-secondary btn-sm"
                      >
                        Upload
                      </button>
                      <input
                        ref={photoRef}
                        type="file"
                        accept="image/*"
                        className="d-none"
                        onChange={onFile("photo")}
                      />
                    </div>
                  </Field>
                </div>
                <div className="col-md-6">
                  <Field label="Signature">
                    <div className="d-flex align-items-center gap-2">
                      <div
                        className="border rounded d-flex align-items-center justify-content-center overflow-hidden flex-shrink-0"
                        style={{ width: 80, height: 44 }}
                      >
                        {form.signature ? (
                          <img
                            src={form.signature}
                            alt=""
                            className="w-100 h-100"
                            style={{ objectFit: "contain" }}
                          />
                        ) : (
                          <span className="text-muted small">—</span>
                        )}
                      </div>
                      <button
                        type="button"
                        onClick={() => sigRef.current?.click()}
                        className="btn btn-outline-secondary btn-sm"
                      >
                        Upload
                      </button>
                      <input
                        ref={sigRef}
                        type="file"
                        accept="image/*"
                        className="d-none"
                        onChange={onFile("signature")}
                      />
                    </div>
                  </Field>
                </div>
              </div>
              <div className="text-end">
                <button
                  type="submit"
                  disabled={saving}
                  className="btn btn-primary btn-sm"
                >
                  {saving ? "Saving…" : "Save setup"}
                </button>
              </div>
            </form>
          </div>
          <div className="col-4 col-xl-4">
            <LetterheadPreview doctor={form} />
          </div>
        </div>
      </div>
    </>
  );
}

export function LetterheadPreview({ doctor }: { doctor: DoctorProfile }) {
  return (
    <div className="card">
      <div className="border rounded overflow-hidden">
        {/* <div className="px-3 py-2 border-bottom bg-light">
          <h6 className="mb-0 small">Letterhead preview</h6>
        </div> */}
        <div className="p-3">
          <div className="d-flex justify-content-between align-items-start border-bottom pb-3 mb-3">
            <div>
              <div className="fw-semibold">
                Dr. {doctor.name || "Your Name"}
              </div>
              <div
                className="text-muted small"
                style={{ whiteSpace: "pre-line" }}
              >
                {doctor.degree || "Degree(s)"}
              </div>
              <div
                className="text-muted small"
                style={{ whiteSpace: "pre-line" }}
              >
                {doctor.specialization || "Specialization"}
              </div>
            </div>
            <div className="text-end">
              <div className="fw-semibold small">
                {doctor.clinic_name || "Clinic / Hospital Name"}
              </div>
              <div className="text-muted small">
                {[doctor.chamber_days, doctor.chamber_hours]
                  .filter(Boolean)
                  .join(" · ") || "Schedule"}
              </div>
            </div>
          </div>
          <p className="text-muted small mb-0">
            This is how your details appear at the top of every printed
            prescription.
          </p>
        </div>
      </div>
    </div>
  );
}
