import { useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { getMe, getProfile, updateProfile, type ProfileUpdate } from "../api/client";

export default function ProfilePage() {
  const queryClient = useQueryClient();
  const [editing, setEditing] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const { data: user } = useQuery({ queryKey: ["me"], queryFn: getMe });
  const { data: profile, isLoading } = useQuery({
    queryKey: ["profile"],
    queryFn: getProfile,
  });

  const [form, setForm] = useState<ProfileUpdate>({});

  const mutation = useMutation({
    mutationFn: updateProfile,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["profile"] });
      setEditing(false);
      setError(null);
    },
    onError: (err: any) => {
      const detail = err?.response?.data?.detail;
      if (Array.isArray(detail)) {
        setError(detail.map((d: any) => d.msg).join("; "));
      } else {
        setError(detail ?? "Failed to save profile");
      }
    },
  });

  const startEditing = () => {
    setForm({
      phone: profile?.phone ?? "",
      date_of_birth: profile?.date_of_birth ?? "",
      position: profile?.position ?? "",
      address: profile?.address ?? "",
    });
    setError(null);
    setEditing(true);
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    // Send null for empty strings so the backend clears the field
    const payload: ProfileUpdate = {};
    for (const [k, v] of Object.entries(form)) {
      (payload as any)[k] = v === "" ? null : v;
    }
    mutation.mutate(payload);
  };

  if (isLoading) return <div style={{ padding: 32 }}>Loading…</div>;

  return (
    <>
      <div style={{ padding: 32, maxWidth: 480 }}>
        <h1>Profile</h1>

        {!editing ? (
          <>
            <table style={{ borderCollapse: "collapse", width: "100%" }}>
              <tbody>
                <Row label="Email" value={user?.email} />
                <Row label="Full name" value={user?.full_name} />
                <Row label="Position" value={profile?.position} />
                <Row label="Phone" value={profile?.phone} />
                <Row label="Date of birth" value={profile?.date_of_birth} />
                <Row label="Address" value={profile?.address} />
              </tbody>
            </table>
            <button onClick={startEditing} style={{ marginTop: 16 }}>
              Edit
            </button>
          </>
        ) : (
          <form onSubmit={handleSubmit}>
            <Field
              label="Position"
              value={form.position ?? ""}
              onChange={(v) => setForm((f) => ({ ...f, position: v }))}
            />
            <Field
              label="Phone"
              value={form.phone ?? ""}
              onChange={(v) => setForm((f) => ({ ...f, phone: v }))}
              type="tel"
            />
            <Field
              label="Date of birth"
              value={form.date_of_birth ?? ""}
              onChange={(v) => setForm((f) => ({ ...f, date_of_birth: v }))}
              type="date"
            />
            <Field
              label="Address"
              value={form.address ?? ""}
              onChange={(v) => setForm((f) => ({ ...f, address: v }))}
            />
            {error && <p style={{ color: "red" }}>{error}</p>}
            <div style={{ display: "flex", gap: 8, marginTop: 16 }}>
              <button type="submit" disabled={mutation.isPending}>
                {mutation.isPending ? "Saving…" : "Save"}
              </button>
              <button type="button" onClick={() => setEditing(false)}>
                Cancel
              </button>
            </div>
          </form>
        )}
      </div>
    </>
  );
}

function Row({ label, value }: { label: string; value?: string | null }) {
  return (
    <tr>
      <td style={{ padding: "6px 12px 6px 0", fontWeight: 600, whiteSpace: "nowrap" }}>
        {label}
      </td>
      <td style={{ padding: "6px 0" }}>{value ?? "—"}</td>
    </tr>
  );
}

function Field({
  label,
  value,
  onChange,
  type = "text",
}: {
  label: string;
  value: string;
  onChange: (v: string) => void;
  type?: string;
}) {
  return (
    <div style={{ marginBottom: 12 }}>
      <label style={{ display: "block", marginBottom: 4 }}>{label}</label>
      <input
        type={type}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        style={{ width: "100%", padding: "6px 8px", boxSizing: "border-box" }}
      />
    </div>
  );
}
