"use client";

import React, { useCallback, useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import DataService from "@/config/axios";
import { getApiErrorMessage } from "@/lib/api-error";
import { isLimitedClientPersona, workspacePersonaFromMe } from "@/lib/workspace-persona";
import { toast } from "sonner";
import avatarPlaceholder from "@/assets/images/avatar.jpeg";

type MeUser = {
  _id?: string;
  firstName?: string;
  lastName?: string;
  email?: string;
  bio?: string;
  phone?: string;
  photo?: string;
  username?: string;
  managementRole?: { name?: string } | string | null;
  linkedProperty?: { name?: string } | string | null;
  client?: Record<string, unknown> | null;
  type?: string;
};

const apiBase = process.env.NEXT_PUBLIC_API_URL || "";

function photoSrc(photo?: string): string {
  if (!photo) return avatarPlaceholder.src;
  if (photo.startsWith("http")) return photo;
  return `${apiBase}${photo.startsWith("/") ? "" : "/"}${photo}`;
}

export default function ProfilePage() {
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [me, setMe] = useState<MeUser | null>(null);
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [email, setEmail] = useState("");
  const [phone, setPhone] = useState("");
  const [bio, setBio] = useState("");
  const [file, setFile] = useState<File | null>(null);
  const [preview, setPreview] = useState<string | null>(null);
  const [limitedProfile, setLimitedProfile] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const res = await DataService.get("/user/me");
      const u = res.data?.data as MeUser | undefined;
      if (!u) {
        toast.error("Could not load profile");
        return;
      }
      setMe(u);
      setFirstName(u.firstName || "");
      setLastName(u.lastName || "");
      setEmail(u.email || "");
      setPhone(u.phone || "");
      setBio(u.bio || "");
      setLimitedProfile(isLimitedClientPersona(workspacePersonaFromMe(u)));
    } catch (e: unknown) {
      toast.error(getApiErrorMessage(e, "Could not load profile"));
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    void load();
  }, [load]);

  useEffect(() => {
    if (!file) {
      setPreview(null);
      return;
    }
    const url = URL.createObjectURL(file);
    setPreview(url);
    return () => URL.revokeObjectURL(url);
  }, [file]);

  const submit = async () => {
    if (!firstName.trim() || !lastName.trim() || !email.trim()) {
      toast.error("First name, last name, and email are required");
      return;
    }
    setSaving(true);
    try {
      if (file) {
        const fd = new FormData();
        fd.append("firstName", firstName.trim());
        fd.append("lastName", lastName.trim());
        fd.append("email", email.trim());
        fd.append("bio", bio);
        fd.append("phone", phone);
        fd.append("photo", file);
        await DataService.patch("/user/me", fd);
      } else {
        await DataService.patch("/user/me", {
          firstName: firstName.trim(),
          lastName: lastName.trim(),
          email: email.trim(),
          bio,
          phone,
        });
      }
      toast.success("Profile updated");
      setFile(null);
      await load();
    } catch (e: unknown) {
      toast.error(getApiErrorMessage(e, "Could not update profile"));
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <div className="rounded-lg border bg-white p-8 text-center text-sm text-muted-foreground">
        Loading profile…
      </div>
    );
  }

  const displayPhoto = preview || photoSrc(me?.photo);

  return (
    <div className="mx-auto max-w-lg space-y-6">
      <Card>
        <CardHeader>
          <CardTitle>Profile</CardTitle>
          <CardDescription>
            {limitedProfile
              ? "You can update your name and photo. Other fields are managed by your organization."
              : "Update your name, contact details, and photo. Changes apply to your account only."}
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-6">
          <div className="flex flex-col items-center gap-3 sm:flex-row sm:items-start">
            <div className="relative size-24 shrink-0 overflow-hidden rounded-full border bg-muted">
              {/* eslint-disable-next-line @next/next/no-img-element -- user uploads / blob previews */}
              <img src={displayPhoto} alt="" className="size-full object-cover" />
            </div>
            <div className="w-full space-y-2">
              <Label htmlFor="profile-photo">Photo</Label>
              <Input
                id="profile-photo"
                type="file"
                accept="image/png,image/jpeg,image/jpg"
                onChange={(e) => {
                  const f = e.target.files?.[0];
                  setFile(f ?? null);
                }}
              />
              <p className="text-xs text-muted-foreground">PNG or JPEG, up to 2 MB.</p>
            </div>
          </div>

          <div className="grid gap-2">
            <Label htmlFor="fn">First name</Label>
            <Input id="fn" value={firstName} onChange={(e) => setFirstName(e.target.value)} autoComplete="given-name" />
          </div>
          <div className="grid gap-2">
            <Label htmlFor="ln">Last name</Label>
            <Input id="ln" value={lastName} onChange={(e) => setLastName(e.target.value)} autoComplete="family-name" />
          </div>
          <div className="grid gap-2">
            <Label htmlFor="em">Email</Label>
            <Input
              id="em"
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              autoComplete="email"
              disabled={limitedProfile}
              className={limitedProfile ? "bg-muted" : undefined}
            />
          </div>
          {!limitedProfile ? (
            <>
              <div className="grid gap-2">
                <Label htmlFor="ph">Phone</Label>
                <Input id="ph" value={phone} onChange={(e) => setPhone(e.target.value)} autoComplete="tel" />
              </div>
              <div className="grid gap-2">
                <Label htmlFor="bio">Bio</Label>
                <Input id="bio" value={bio} onChange={(e) => setBio(e.target.value)} />
              </div>
            </>
          ) : null}

          <Button type="button" className="w-full sm:w-auto" disabled={saving} onClick={() => void submit()}>
            {saving ? "Saving…" : "Update profile"}
          </Button>
        </CardContent>
      </Card>
    </div>
  );
}
