"use client";
import { useState } from "react";
import CommonInputField from "@/app/components/CommonInputField";
import CommonTextArea from "@/app/components/CommonTextArea";
import CommonFileUpload from "@/app/components/CommonFileUpload";
import CommonSubmitButton from "@/app/components/CommonSubmitButton";
import CommonError from "@/app/components/CommonError";
import { DoctorProfile } from "../_types";
import { saveDoctorProfile } from "../_api";
import { useHms } from "../layout";

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 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") => (files: File[]) => {
    const f = 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.");
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="row g-4">
      <div className="col-12 col-xl-7">
        <h5 className="mb-1">Doctor Setup</h5>
        <p className="text-muted small mb-3">Clinic letterhead info used on every printed prescription</p>
        <CommonError message={saved} type="" />
        <form onSubmit={save} className="border rounded p-3">
          <div className="mb-3"><CommonFileUpload label="Hospital logo" onFilesChange={onFile("logo")} accept={{ "image/*": [] }} maxFiles={1} /></div>
          <div className="row g-3 mb-3">
            <div className="col-md-6"><CommonInputField level_name="Your name" value={form.name} on_change_data={set("name")} required /></div>
            <div className="col-md-6"><CommonInputField level_name="Clinic / hospital name" value={form.clinic_name} on_change_data={set("clinic_name")} /></div>
          </div>
          <div className="row g-3 mb-3">
            <div className="col-md-6"><CommonInputField level_name="Registration no." value={form.registration_no} on_change_data={set("registration_no")} /></div>
            <div className="col-md-6"><CommonInputField level_name="Contact" value={form.contact} on_change_data={set("contact")} /></div>
          </div>
          <div className="mb-3"><CommonTextArea level_name="Specialization" rows={2} value={form.specialization} on_change_data={set("specialization")} /></div>
          <div className="mb-3"><CommonTextArea level_name="Degree(s)" rows={2} value={form.degree} on_change_data={set("degree")} /></div>
          <div className="mb-3"><CommonTextArea level_name="Clinic address" rows={2} value={form.clinic_address} on_change_data={set("clinic_address")} /></div>
          <div className="row g-3 mb-3">
            <div className="col-md-6"><CommonInputField level_name="Chamber days" value={form.chamber_days} on_change_data={set("chamber_days")} placeholder="Sat – Thu" /></div>
            <div className="col-md-6"><CommonInputField level_name="Chamber hours" value={form.chamber_hours} on_change_data={set("chamber_hours")} placeholder="5:00 PM – 9:00 PM" /></div>
          </div>
          <div className="row g-3 mb-3">
            <div className="col-md-6"><CommonFileUpload label="Photo" onFilesChange={onFile("photo")} accept={{ "image/*": [] }} maxFiles={1} /></div>
            <div className="col-md-6"><CommonFileUpload label="Signature" onFilesChange={onFile("signature")} accept={{ "image/*": [] }} maxFiles={1} /></div>
          </div>
          <div className="text-end"><CommonSubmitButton label="Save setup" loading={saving} /></div>
        </form>
      </div>
      <div className="col-12 col-xl-5">
        <LetterheadPreview doctor={form} />
      </div>
    </div>
  );
}

export function LetterheadPreview({ doctor }: { doctor: DoctorProfile }) {
  return (
    <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>
  );
}
