import { useEffect, useRef, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import {
  Camera, Loader2, Trash2, User as UserIcon, ArrowLeft, Save, AlertCircle, CheckCircle2,
} from "lucide-react";
import SiteLayout from "@/components/SiteLayout";
import { useUserProfile } from "@/hooks/useUserProfile";
import { useWhmcsProfile } from "@/hooks/useWhmcsProfile";
import { client } from "@/lib/api";

const MAX_SIZE_BYTES = 5 * 1024 * 1024;
const ACCEPTED_TYPES = ["image/png", "image/jpeg", "image/jpg", "image/webp", "image/gif"];

interface EditableProfile {
  firstname: string;
  lastname: string;
  companyname: string;
  address1: string;
  address2: string;
  city: string;
  state: string;
  postcode: string;
  country: string;
  phonenumber: string;
}

const EMPTY: EditableProfile = {
  firstname: "",
  lastname: "",
  companyname: "",
  address1: "",
  address2: "",
  city: "",
  state: "",
  postcode: "",
  country: "",
  phonenumber: "",
};

export default function ProfileSettings() {
  const navigate = useNavigate();
  const { loading: authLoading, authed, user, avatarUrl, uploadAvatar, removeAvatar } = useUserProfile();
  const { loading: whmcsLoading, profile, notLinked, error: profileError, refetch } = useWhmcsProfile();
  const fileRef = useRef<HTMLInputElement>(null);

  const [avatarBusy, setAvatarBusy] = useState(false);
  const [avatarError, setAvatarError] = useState<string | null>(null);
  const [avatarSuccess, setAvatarSuccess] = useState<string | null>(null);

  const [formDraft, setFormDraft] = useState<EditableProfile>(EMPTY);
  const [saving, setSaving] = useState(false);
  const [saveError, setSaveError] = useState<string | null>(null);
  const [saveSuccess, setSaveSuccess] = useState<string | null>(null);

  useEffect(() => {
    if (profile) {
      setFormDraft({
        firstname: profile.firstname || "",
        lastname: profile.lastname || "",
        companyname: profile.company || "",
        address1: profile.address1 || "",
        address2: profile.address2 || "",
        city: profile.city || "",
        state: profile.state || "",
        postcode: profile.postcode || "",
        country: profile.country || "",
        phonenumber: profile.phonenumber || "",
      });
    }
  }, [profile]);

  const update = <K extends keyof EditableProfile>(k: K, v: EditableProfile[K]) =>
    setFormDraft((prev) => ({ ...prev, [k]: v }));

  const handleFile = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    event.target.value = "";
    if (!file) return;
    setAvatarError(null);
    setAvatarSuccess(null);

    if (!ACCEPTED_TYPES.includes(file.type)) {
      setAvatarError("Please choose a PNG, JPG, WebP, or GIF image.");
      return;
    }
    if (file.size > MAX_SIZE_BYTES) {
      setAvatarError("Image must be smaller than 5 MB.");
      return;
    }

    try {
      setAvatarBusy(true);
      await uploadAvatar(file);
      setAvatarSuccess("Profile picture updated.");
    } catch (err) {
      console.error(err);
      setAvatarError(err instanceof Error ? err.message : "Failed to upload avatar.");
    } finally {
      setAvatarBusy(false);
    }
  };

  const handleRemove = async () => {
    setAvatarError(null);
    setAvatarSuccess(null);
    try {
      setAvatarBusy(true);
      await removeAvatar();
      setAvatarSuccess("Profile picture removed.");
    } catch (err) {
      console.error(err);
      setAvatarError(err instanceof Error ? err.message : "Failed to remove avatar.");
    } finally {
      setAvatarBusy(false);
    }
  };

  const handleSave = async (event: React.FormEvent) => {
    event.preventDefault();
    setSaveError(null);
    setSaveSuccess(null);

    if (!formDraft.firstname.trim() || !formDraft.lastname.trim()) {
      setSaveError("First name and last name are required.");
      return;
    }

    setSaving(true);
    try {
      await client.apiCall.invoke({
        url: "/api/v1/whmcs/update-profile",
        method: "POST",
        data: {
          firstname: formDraft.firstname.trim(),
          lastname: formDraft.lastname.trim(),
          companyname: formDraft.companyname.trim() || null,
          address1: formDraft.address1.trim() || null,
          address2: formDraft.address2.trim() || null,
          city: formDraft.city.trim() || null,
          state: formDraft.state.trim() || null,
          postcode: formDraft.postcode.trim() || null,
          country: formDraft.country.trim() ? formDraft.country.trim().toUpperCase() : null,
          phonenumber: formDraft.phonenumber.trim() || null,
        },
      });
      setSaveSuccess("Profile updated in WHMCS.");
      await refetch();
    } catch (err: unknown) {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const anyErr = err as any;
      setSaveError(
        anyErr?.response?.data?.detail ||
          anyErr?.message ||
          "Failed to update profile. Please try again.",
      );
    } finally {
      setSaving(false);
    }
  };

  const inputClass =
    "w-full px-3 py-2 rounded-md border border-slate-300 bg-white text-sm text-slate-900 focus:outline-none focus:ring-2 focus:ring-[#0b6e3e]/30";

  return (
    <SiteLayout>
      <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-10 space-y-8">
        <Link
          to="/client"
          className="inline-flex items-center gap-2 text-sm text-[#0b6e3e] font-semibold hover:underline"
        >
          <ArrowLeft className="w-4 h-4" /> Back to dashboard
        </Link>

        {/* AVATAR CARD */}
        <section className="bg-white rounded-2xl border border-slate-200 shadow-sm p-6 sm:p-8">
          <h1 className="text-2xl font-bold text-slate-900">Account Settings</h1>
          <p className="text-sm text-slate-500 mt-1">
            Manage your profile picture and your WHMCS client details.
          </p>

          {authLoading ? (
            <div className="flex items-center gap-2 text-slate-500 mt-8">
              <Loader2 className="w-5 h-5 animate-spin" /> Loading account…
            </div>
          ) : !authed ? (
            <div className="mt-8 p-6 rounded-xl border border-dashed border-slate-300 bg-slate-50 text-center">
              <p className="text-slate-700 font-semibold">You must be signed in to update your profile.</p>
              <button
                onClick={() => navigate("/login")}
                className="mt-4 px-5 py-2 rounded-md bg-[#0b6e3e] text-white font-bold text-sm hover:bg-[#0a8048] transition"
              >
                Sign in
              </button>
            </div>
          ) : (
            <div className="mt-8 flex flex-col sm:flex-row items-center gap-6">
              <div className="w-28 h-28 rounded-full border-2 border-[#0b6e3e] bg-slate-100 overflow-hidden flex items-center justify-center shrink-0">
                {avatarUrl ? (
                  <img src={avatarUrl} alt="Profile" className="w-full h-full object-cover" />
                ) : (
                  <UserIcon className="w-12 h-12 text-[#0b6e3e]" />
                )}
              </div>

              <div className="flex-1 w-full">
                <p className="font-bold text-slate-900">
                  {profile?.fullname || user?.name || user?.email || "Your account"}
                </p>
                {user?.email && <p className="text-sm text-slate-500">{user.email}</p>}

                <div className="mt-4 flex flex-wrap gap-3">
                  <button
                    onClick={() => fileRef.current?.click()}
                    disabled={avatarBusy}
                    className="inline-flex items-center gap-2 px-4 py-2 rounded-md bg-[#0b6e3e] text-white font-semibold text-sm hover:bg-[#0a8048] disabled:opacity-60 transition"
                  >
                    {avatarBusy ? (
                      <Loader2 className="w-4 h-4 animate-spin" />
                    ) : (
                      <Camera className="w-4 h-4" />
                    )}
                    {avatarUrl ? "Change picture" : "Upload picture"}
                  </button>
                  {avatarUrl && (
                    <button
                      onClick={handleRemove}
                      disabled={avatarBusy}
                      className="inline-flex items-center gap-2 px-4 py-2 rounded-md border border-slate-300 text-slate-700 font-semibold text-sm hover:bg-slate-50 disabled:opacity-60 transition"
                    >
                      <Trash2 className="w-4 h-4" /> Remove
                    </button>
                  )}
                </div>

                <p className="text-xs text-slate-500 mt-3">PNG, JPG, WebP, or GIF. Max size 5 MB.</p>
                {avatarError && (
                  <div className="mt-3 p-2 rounded bg-red-50 border border-red-200 text-xs text-red-700">
                    {avatarError}
                  </div>
                )}
                {avatarSuccess && (
                  <div className="mt-3 p-2 rounded bg-emerald-50 border border-emerald-200 text-xs text-emerald-700">
                    {avatarSuccess}
                  </div>
                )}

                <input
                  ref={fileRef}
                  type="file"
                  accept={ACCEPTED_TYPES.join(",")}
                  className="hidden"
                  onChange={handleFile}
                />
              </div>
            </div>
          )}
        </section>

        {/* WHMCS PROFILE */}
        {authed && (
          <section className="bg-white rounded-2xl border border-slate-200 shadow-sm p-6 sm:p-8">
            <h2 className="text-xl font-bold text-slate-900">Client details</h2>
            <p className="text-sm text-slate-500 mt-1">
              These details are stored in WHMCS and used for billing and support.
            </p>

            {whmcsLoading ? (
              <div className="flex items-center gap-2 text-slate-500 mt-6">
                <Loader2 className="w-4 h-4 animate-spin" /> Loading WHMCS profile…
              </div>
            ) : notLinked ? (
              <div className="mt-6 p-6 rounded-xl border border-dashed border-amber-300 bg-amber-50 text-center">
                <AlertCircle className="w-8 h-8 mx-auto text-amber-500 mb-2" />
                <p className="text-sm text-slate-800 font-semibold">No WHMCS client linked yet.</p>
                <Link
                  to="/register"
                  className="mt-4 inline-block px-5 py-2 rounded-md bg-[#0b6e3e] text-white font-bold text-sm hover:bg-[#0a8048] transition"
                >
                  Complete registration
                </Link>
              </div>
            ) : profileError ? (
              <div className="mt-6 p-4 rounded-lg bg-red-50 border border-red-200 text-sm text-red-700 flex items-start gap-2">
                <AlertCircle className="w-4 h-4 shrink-0 mt-0.5" /> {profileError}
              </div>
            ) : (
              <form onSubmit={handleSave} className="mt-6 space-y-5">
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <label className="block">
                    <span className="text-xs font-semibold text-slate-700 mb-1 block">First name</span>
                    <input
                      className={inputClass}
                      value={formDraft.firstname}
                      onChange={(e) => update("firstname", e.target.value)}
                    />
                  </label>
                  <label className="block">
                    <span className="text-xs font-semibold text-slate-700 mb-1 block">Last name</span>
                    <input
                      className={inputClass}
                      value={formDraft.lastname}
                      onChange={(e) => update("lastname", e.target.value)}
                    />
                  </label>
                </div>

                <label className="block">
                  <span className="text-xs font-semibold text-slate-700 mb-1 block">Email (read-only)</span>
                  <input
                    className={`${inputClass} bg-slate-50 cursor-not-allowed`}
                    value={profile?.email || user?.email || ""}
                    readOnly
                  />
                  <span className="text-[11px] text-slate-500 mt-1 block">
                    Email is linked to your DoItEasy sign-in and cannot be edited here.
                  </span>
                </label>

                <label className="block">
                  <span className="text-xs font-semibold text-slate-700 mb-1 block">Company</span>
                  <input
                    className={inputClass}
                    value={formDraft.companyname}
                    onChange={(e) => update("companyname", e.target.value)}
                  />
                </label>

                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <label className="block">
                    <span className="text-xs font-semibold text-slate-700 mb-1 block">Address line 1</span>
                    <input
                      className={inputClass}
                      value={formDraft.address1}
                      onChange={(e) => update("address1", e.target.value)}
                    />
                  </label>
                  <label className="block">
                    <span className="text-xs font-semibold text-slate-700 mb-1 block">Address line 2</span>
                    <input
                      className={inputClass}
                      value={formDraft.address2}
                      onChange={(e) => update("address2", e.target.value)}
                    />
                  </label>
                </div>

                <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                  <label className="block">
                    <span className="text-xs font-semibold text-slate-700 mb-1 block">City</span>
                    <input
                      className={inputClass}
                      value={formDraft.city}
                      onChange={(e) => update("city", e.target.value)}
                    />
                  </label>
                  <label className="block">
                    <span className="text-xs font-semibold text-slate-700 mb-1 block">State / Region</span>
                    <input
                      className={inputClass}
                      value={formDraft.state}
                      onChange={(e) => update("state", e.target.value)}
                    />
                  </label>
                  <label className="block">
                    <span className="text-xs font-semibold text-slate-700 mb-1 block">Postcode</span>
                    <input
                      className={inputClass}
                      value={formDraft.postcode}
                      onChange={(e) => update("postcode", e.target.value)}
                    />
                  </label>
                </div>

                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <label className="block">
                    <span className="text-xs font-semibold text-slate-700 mb-1 block">
                      Country (ISO-2 code)
                    </span>
                    <input
                      className={inputClass}
                      value={formDraft.country}
                      onChange={(e) => update("country", e.target.value.toUpperCase().slice(0, 2))}
                      placeholder="SA"
                      maxLength={2}
                    />
                  </label>
                  <label className="block">
                    <span className="text-xs font-semibold text-slate-700 mb-1 block">Phone</span>
                    <input
                      className={inputClass}
                      value={formDraft.phonenumber}
                      onChange={(e) => update("phonenumber", e.target.value)}
                    />
                  </label>
                </div>

                {saveError && (
                  <div className="p-3 rounded bg-red-50 border border-red-200 text-sm text-red-700 flex items-start gap-2">
                    <AlertCircle className="w-4 h-4 shrink-0 mt-0.5" /> {saveError}
                  </div>
                )}
                {saveSuccess && (
                  <div className="p-3 rounded bg-emerald-50 border border-emerald-200 text-sm text-emerald-700 flex items-start gap-2">
                    <CheckCircle2 className="w-4 h-4 shrink-0 mt-0.5" /> {saveSuccess}
                  </div>
                )}

                <div className="flex justify-end">
                  <button
                    type="submit"
                    disabled={saving}
                    className="inline-flex items-center gap-2 px-5 py-2.5 rounded-md bg-[#0b6e3e] text-white font-bold text-sm hover:bg-[#0a8048] disabled:opacity-60 transition"
                  >
                    {saving ? (
                      <Loader2 className="w-4 h-4 animate-spin" />
                    ) : (
                      <Save className="w-4 h-4" />
                    )}
                    Save changes
                  </button>
                </div>
              </form>
            )}
          </section>
        )}
      </div>
    </SiteLayout>
  );
}