"use client";

import { useEffect, useState, useCallback } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import { createClient } from "@/lib/supabase/client";
import Card, { CardHeader } from "@/components/ui/Card";
import Button from "@/components/ui/Button";
import Spinner from "@/components/ui/Spinner";
import { Field, Input } from "@/components/ui/Input";
import Chips from "@/components/ui/Chips";
import Modal from "@/components/ui/Modal";
import { useToast } from "@/components/ui/Toast";
import { formatDate } from "@/lib/format";
import { UserCircle, ShieldCheck, IdCard, CalendarDays, Award, Image as ImageIcon, Camera, Send } from "lucide-react";

type Profile = {
  id: string;
  full_name: string;
  staff_id: string | null;
  matric_no: string | null;
  email: string;
  phone: string | null;
  role: string;
  total_merit: number;
  created_at: string;
  avatar_url: string | null;
  telegram_chat_id: string | null;
};

type Skill = { id: string; name: string };

const AVATAR_PRESETS = [
  "/avatars/avatar_male_songkok.png",
  "/avatars/avatar_female_hijab_1.png",
  "/avatars/avatar_male_kopiah.png",
  "/avatars/avatar_female_hijab_2.png",
  "/avatars/avatar_male_songkok_glasses.png",
  "/avatars/avatar_female_hijab_3.png",
];

export default function ProfilePage() {
  const supabase = createClient();
  const searchParams = useSearchParams();
  const router = useRouter();
  const { notify } = useToast();

  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [profile, setProfile] = useState<Profile | null>(null);

  // Common form inputs
  const [fullName, setFullName] = useState("");
  const [phone, setPhone] = useState("");
  const [avatarUrl, setAvatarUrl] = useState("");

  // Role specific form inputs
  const [staffId, setStaffId] = useState("");
  const [matricNo, setMatricNo] = useState("");

  // Skills
  const [availableSkills, setAvailableSkills] = useState<Skill[]>([]);
  const [selectedSkills, setSelectedSkills] = useState<string[]>([]);
  const [originalSkills, setOriginalSkills] = useState<string[]>([]);

  // System settings (Admin only)
  const [loginBgUrl, setLoginBgUrl] = useState("");
  const [originalLoginBg, setOriginalLoginBg] = useState("");
  const [savingConfig, setSavingConfig] = useState(false);

  // Avatar Modal
  const [avatarModalOpen, setAvatarModalOpen] = useState(false);
  const [customAvatarInput, setCustomAvatarInput] = useState("");

  // Telegram integration (Volunteer only)
  const [telegramChatId, setTelegramChatId] = useState("");
  const [testingTg, setTestingTg] = useState(false);
  const [disconnectingTg, setDisconnectingTg] = useState(false);

  const load = useCallback(async () => {
    const { data: userRes } = await supabase.auth.getUser();
    if (!userRes.user) {
      router.push("/login");
      return;
    }

    const [profileRes, skillsRes, mySkillsRes, configRes] = await Promise.all([
      supabase
        .from("profiles")
        .select("*")
        .eq("id", userRes.user.id)
        .single(),
      supabase.from("skills").select("id, name").order("name"),
      supabase.from("volunteer_skills").select("skill_id").eq("volunteer_id", userRes.user.id),
      supabase
        .from("app_config")
        .select("value")
        .eq("key", "login_page_image_url")
        .maybeSingle()
    ]);

    if (profileRes.data) {
      const p = profileRes.data as any;
      setProfile(p);
      setFullName(p.full_name ?? "");
      setPhone(p.phone ?? "");
      setStaffId(p.staff_id ?? "");
      setMatricNo(p.matric_no ?? "");
      setAvatarUrl(p.avatar_url ?? "");
      setCustomAvatarInput(p.avatar_url ?? "");
      setTelegramChatId(p.telegram_chat_id ?? "");

      // Skills mapping
      setAvailableSkills((skillsRes.data as Skill[]) ?? []);
      const skIds = (mySkillsRes.data ?? []).map((row: any) => row.skill_id);
      setSelectedSkills(skIds);
      setOriginalSkills(skIds);
    }

    if (configRes.data) {
      setLoginBgUrl(configRes.data.value);
      setOriginalLoginBg(configRes.data.value);
    } else {
      setLoginBgUrl("/mosque_login.png");
      setOriginalLoginBg("/mosque_login.png");
    }

    setLoading(false);
  }, [supabase, router]);

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

  function toggleSkill(id: string) {
    setSelectedSkills((s) => (s.includes(id) ? s.filter((x) => x !== id) : [...s, id]));
  }

  // Generate a unique deep-link every time so Telegram always re-fires /start
  // even if the user previously started the bot (fixes the reconnect bug).
  function getTelegramDeepLink() {
    if (!profile) return "#";
    const rand = Math.random().toString(36).slice(2, 8);
    return `https://t.me/PusatIslamUPSI_bot?start=${profile.id}_${rand}`;
  }

  async function checkTelegramStatus() {
    if (!profile) return;
    setTestingTg(true);
    try {
      const { data, error } = await supabase
        .from("profiles")
        .select("telegram_chat_id")
        .eq("id", profile.id)
        .single();
      if (error) throw error;
      const newChatId = data?.telegram_chat_id ?? "";
      setTelegramChatId(newChatId);
      setProfile((prev: any) => prev ? { ...prev, telegram_chat_id: newChatId || null } : null);
      if (newChatId) {
        notify("Connected! Your Telegram account is linked.", "success");
      } else {
        notify("Not connected yet. Open the bot and tap Start first.", "error");
      }
    } catch (err: any) {
      notify("Failed to check status: " + err.message, "error");
    } finally {
      setTestingTg(false);
    }
  }

  async function disconnectTelegram() {
    if (!profile) return;
    setDisconnectingTg(true);
    try {
      const { error } = await supabase
        .from("profiles")
        .update({ telegram_chat_id: null })
        .eq("id", profile.id);
      if (error) throw error;
      setTelegramChatId("");
      setProfile((prev: any) => prev ? { ...prev, telegram_chat_id: null } : null);
      notify("Telegram disconnected successfully.");
    } catch (err: any) {
      notify("Failed to disconnect: " + err.message, "error");
    } finally {
      setDisconnectingTg(false);
    }
  }

  async function save(e: React.FormEvent) {
    e.preventDefault();
    if (!profile) return;
    if (!fullName.trim()) return notify("Full name cannot be empty.", "error");
    if (!phone.trim()) return notify("Phone number is mandatory.", "error");

    setSaving(true);

    const updatePayload: any = {
      full_name: fullName.trim(),
      phone: phone.trim() || null,
      avatar_url: avatarUrl.trim() || null,
    };

    if (profile.role === "admin") {
      updatePayload.staff_id = staffId.trim() || null;
    } else {
      updatePayload.matric_no = matricNo.trim() || null;
      updatePayload.telegram_chat_id = telegramChatId.trim() || null;
    }

    const { error: profileError } = await supabase
      .from("profiles")
      .update(updatePayload)
      .eq("id", profile.id);

    if (profileError) {
      setSaving(false);
      return notify(profileError.message, "error");
    }

    // Update skills for student volunteer
    if (profile.role === "volunteer") {
      await supabase.from("volunteer_skills").delete().eq("volunteer_id", profile.id);
      if (selectedSkills.length > 0) {
        const rows = selectedSkills.map((sid) => ({
          volunteer_id: profile.id,
          skill_id: sid,
        }));
        const { error: skillsError } = await supabase.from("volunteer_skills").insert(rows);
        if (skillsError) {
          console.error("Failed to save volunteer skills:", skillsError.message);
        }
      }
    }

    setSaving(false);
    notify("Profile updated successfully!");
 
    // Broadcast the new avatar immediately so the Topbar (a sibling
    // component, not a parent/child) updates without needing a logout,
    // login, or even a page navigation.
    window.dispatchEvent(
      new CustomEvent("profile-avatar-updated", {
        detail: { avatarUrl: updatePayload.avatar_url ?? null },
      })
    );
 
    router.refresh();
    load();
  }

  async function saveSystemConfig(e: React.FormEvent) {
    e.preventDefault();
    setSavingConfig(true);
    const { error } = await supabase
      .from("app_config")
      .upsert({
        key: "login_page_image_url",
        value: loginBgUrl.trim() || "/mosque_login.png",
      });
    setSavingConfig(false);
    if (error) {
      notify(error.message, "error");
    } else {
      notify("System configuration updated successfully!");
      load();
    }
  }

  if (loading) return <Spinner label="Loading profile…" />;
  if (!profile) return <p className="text-sm text-muted">Could not load your profile.</p>;

  const initials = (profile.full_name || "AD")
    .split(" ")
    .map((n) => n[0])
    .slice(0, 2)
    .join("")
    .toUpperCase();

  const skillsDirty =
    profile.role === "volunteer" &&
    (selectedSkills.length !== originalSkills.length ||
      selectedSkills.some((s) => !originalSkills.includes(s)));

  const dirty =
    fullName !== (profile.full_name ?? "") ||
    phone !== (profile.phone ?? "") ||
    avatarUrl !== (profile.avatar_url ?? "") ||
    (profile.role === "admin" && staffId !== (profile.staff_id ?? "")) ||
    (profile.role === "volunteer" && matricNo !== (profile.matric_no ?? "")) ||
    (profile.role === "volunteer" && telegramChatId !== (profile.telegram_chat_id ?? "")) ||
    skillsDirty;

  const configDirty = loginBgUrl !== originalLoginBg;

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-extrabold text-ink">My Profile</h1>
        <p className="text-sm text-muted">
          {profile.role === "admin"
            ? "View and update your admin details and portal settings."
            : "Manage your personal volunteer profile and skills selection."}
        </p>
      </div>

      <div className="grid gap-6 lg:grid-cols-3">
        {/* Left Column: Summary card */}
        <div className="space-y-6 lg:col-span-1">
          <Card>
            <div className="flex flex-col items-center p-6 text-center">
              {/* Profile Picture with Edit Overlay */}
              <div className="relative group">
                {avatarUrl ? (
                  <img
                    src={avatarUrl}
                    alt={profile.full_name}
                    className="h-24 w-24 rounded-full border border-sand-dark shadow-md object-cover"
                  />
                ) : (
                  <div className="flex h-24 w-24 items-center justify-center rounded-full bg-emerald text-3xl font-extrabold text-white shadow-md">
                    {initials}
                  </div>
                )}
                <button
                  onClick={() => setAvatarModalOpen(true)}
                  type="button"
                  className="absolute inset-0 flex h-24 w-24 items-center justify-center rounded-full bg-black/40 text-white opacity-0 group-hover:opacity-100 transition-opacity duration-200 cursor-pointer"
                  title="Change profile picture"
                >
                  <Camera size={20} />
                </button>
              </div>

              <p className="mt-4 text-lg font-bold text-ink">{profile.full_name}</p>
              <p className="text-sm text-muted">{profile.email}</p>

              <div className="mt-5 w-full space-y-3 text-left">
                <Row icon={<ShieldCheck size={16} className="text-emerald" />} label="Role">
                  <span className="capitalize">{profile.role === "volunteer" ? "student" : profile.role}</span>
                </Row>

                {profile.role === "admin" ? (
                  <Row icon={<IdCard size={16} className="text-teal" />} label="Staff ID">
                    {profile.staff_id || "—"}
                  </Row>
                ) : (
                  <>
                    <Row icon={<IdCard size={16} className="text-teal" />} label="Matric No.">
                      {profile.matric_no || "—"}
                    </Row>
                    <Row icon={<Award size={16} className="text-warning" />} label="Merit points">
                      {profile.total_merit} MP
                    </Row>
                    <Row icon={<Send size={16} className={telegramChatId ? "text-emerald" : "text-muted"} />} label="Telegram">
                      {telegramChatId ? (
                        <span className="inline-flex items-center rounded-full bg-emerald-light px-2 py-0.5 text-[10px] font-bold text-emerald">✓ Connected</span>
                      ) : (
                        <span className="text-muted text-xs">Not connected</span>
                      )}
                    </Row>
                  </>
                )}

                <Row icon={<CalendarDays size={16} className="text-muted" />} label="Member since">
                  {formatDate(profile.created_at)}
                </Row>
              </div>
            </div>
          </Card>

          {/* Admin System configurations (Admin only) */}
          {profile.role === "admin" && (
            <Card>
              <CardHeader title="System Configuration" />
              <form onSubmit={saveSystemConfig} className="p-5 space-y-4">
                <Field
                  label="Login Background Image URL"
                  hint="Custom graphic displayed in the left panel of the login page."
                >
                  <Input
                    value={loginBgUrl}
                    onChange={(e) => setLoginBgUrl(e.target.value)}
                    placeholder="e.g. /mosque_login.png or https://..."
                  />
                </Field>
                <div className="flex justify-end pt-1">
                  <Button type="submit" disabled={!configDirty || savingConfig}>
                    {savingConfig ? "Saving..." : "Save System Config"}
                  </Button>
                </div>
              </form>
            </Card>
          )}

          {/* Telegram Reminders Card — inside left column for volunteers */}
          {profile.role === "volunteer" && (
            <Card>
              <CardHeader title="Telegram Reminders" />
              <div className="p-4 space-y-4">
                {/* Status pill */}
                <div className="flex items-center gap-3 rounded-xl border border-sand-dark/40 bg-sand/40 px-3 py-3">
                  <div className={`flex h-9 w-9 shrink-0 items-center justify-center rounded-full ${
                    telegramChatId ? "bg-emerald" : "bg-sand-dark/50"
                  }`}>
                    <Send size={15} className={telegramChatId ? "text-white" : "text-muted"} />
                  </div>
                  <div className="min-w-0">
                    <p className="text-sm font-semibold text-ink leading-tight">
                      {telegramChatId ? "Connected" : "Not connected"}
                    </p>
                    <p className="text-xs text-muted leading-snug mt-0.5">
                      {telegramChatId
                        ? "Reminders will arrive on Telegram."
                        : "Link Telegram to get instant reminders."}
                    </p>
                  </div>
                </div>

                {/* Action buttons */}
                {!telegramChatId ? (
                  <div className="space-y-2">
                    <a
                      href={getTelegramDeepLink()}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="flex w-full items-center justify-center gap-2 rounded-xl bg-emerald px-4 py-2.5 text-sm font-bold text-white hover:bg-emerald-dark transition-all shadow-sm"
                    >
                      <Send size={14} /> Connect Telegram
                    </a>
                    <button
                      type="button"
                      onClick={checkTelegramStatus}
                      disabled={testingTg}
                      className="flex w-full items-center justify-center rounded-xl border border-sand-dark bg-white px-4 py-2 text-sm font-semibold text-muted hover:bg-sand transition-all disabled:opacity-50"
                    >
                      {testingTg ? "Checking…" : "Check Connection"}
                    </button>
                    <p className="text-[11px] text-muted text-center leading-relaxed">
                      Tap <strong>Connect</strong> → tap <strong>Start</strong> in bot → tap <strong>Check Connection</strong>
                    </p>
                  </div>
                ) : (
                  <div className="space-y-2">
                    <a
                      href={getTelegramDeepLink()}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="flex w-full items-center justify-center gap-2 rounded-xl border border-emerald bg-white px-4 py-2.5 text-sm font-bold text-emerald hover:bg-emerald-light/30 transition-all"
                    >
                      <Send size={14} /> Reconnect
                    </a>
                    <div className="flex gap-2">
                      <button
                        type="button"
                        onClick={checkTelegramStatus}
                        disabled={testingTg}
                        className="flex-1 rounded-xl border border-sand-dark bg-white px-3 py-2 text-xs font-semibold text-muted hover:bg-sand transition-all disabled:opacity-50"
                      >
                        {testingTg ? "Checking…" : "Refresh"}
                      </button>
                      <button
                        type="button"
                        onClick={disconnectTelegram}
                        disabled={disconnectingTg}
                        className="flex-1 rounded-xl border border-red-200 bg-white px-3 py-2 text-xs font-semibold text-red-500 hover:bg-red-50 transition-all disabled:opacity-50"
                      >
                        {disconnectingTg ? "…" : "Disconnect"}
                      </button>
                    </div>
                  </div>
                )}
              </div>
            </Card>
          )}
        </div>

        {/* Right Column: Edit form */}
        <Card className="lg:col-span-2">
          <CardHeader title="Edit profile details" />
          <form onSubmit={save} className="space-y-4 p-5">
            <Field label="Full name">
              <Input value={fullName} onChange={(e) => setFullName(e.target.value)} required />
            </Field>

            {profile.role === "admin" ? (
              <Field label="Staff ID">
                <Input
                  value={staffId}
                  onChange={(e) => setStaffId(e.target.value)}
                  placeholder="e.g. UPSI-PI-0123"
                />
              </Field>
            ) : (
              <Field label="Matric No.">
                <Input
                  value={matricNo}
                  onChange={(e) => setMatricNo(e.target.value)}
                  placeholder="e.g. D20231106439"
                />
              </Field>
            )}

            <Field label="Phone" hint="Mandatory">
              <Input
                value={phone}
                onChange={(e) => setPhone(e.target.value)}
                placeholder="012-3456789"
                required
              />
            </Field>

            <Field label="Email" hint="Email is tied to your account and cannot be updated here.">
              <Input value={profile.email} disabled className="bg-sand/50" />
            </Field>

            {profile.role === "volunteer" && (
              <Field label="My Skills Selection" hint="Select skills you can offer for Pusat Islam programs.">
                <Chips
                  options={availableSkills}
                  selected={selectedSkills}
                  onToggle={toggleSkill}
                />
              </Field>
            )}

            <div className="flex justify-end gap-2 pt-2">
              <Button
                type="button"
                variant="secondary"
                disabled={!dirty || saving}
                onClick={() => {
                  setFullName(profile.full_name ?? "");
                  setPhone(profile.phone ?? "");
                  setStaffId(profile.staff_id ?? "");
                  setMatricNo(profile.matric_no ?? "");
                  setAvatarUrl(profile.avatar_url ?? "");
                  setSelectedSkills(originalSkills);
                  setTelegramChatId(profile.telegram_chat_id ?? "");
                }}
              >
                Reset
              </Button>
              <Button type="submit" disabled={!dirty || saving}>
                {saving ? "Saving…" : "Save changes"}
              </Button>
            </div>
          </form>
        </Card>
      </div>

      {/* Edit Avatar Modal */}
      <Modal open={avatarModalOpen} onClose={() => setAvatarModalOpen(false)} title="Select Profile Avatar">
        <div className="space-y-5 p-1">
          <div>
            <p className="text-xs font-bold text-muted uppercase tracking-wider mb-2">Preset Avatars</p>
            <div className="grid grid-cols-3 gap-4">
              {AVATAR_PRESETS.map((preset, idx) => (
                <button
                  key={idx}
                  type="button"
                  onClick={() => {
                    setAvatarUrl(preset);
                    setAvatarModalOpen(false);
                  }}
                  className={`relative p-1 rounded-card border-2 hover:border-emerald transition-colors ${
                    avatarUrl === preset ? "border-emerald bg-emerald-light/20" : "border-sand-dark"
                  }`}
                >
                  <img src={preset} alt={`Preset ${idx + 1}`} className="h-20 w-20 mx-auto object-cover" />
                </button>
              ))}
            </div>
          </div>

          <div className="border-t border-sand-light pt-4">
            <p className="text-xs font-bold text-muted uppercase tracking-wider mb-2">Select From Program Assets</p>
            <div className="grid grid-cols-4 gap-2">
              {[
                "/assets/masjid_cleanup.png",
                "/assets/quran_study.png",
                "/assets/food_charity.png",
                "/assets/media_crew.png"
              ].map((assetPath) => (
                <button
                  key={assetPath}
                  type="button"
                  onClick={() => {
                    setAvatarUrl(assetPath);
                    setAvatarModalOpen(false);
                  }}
                  className={`relative p-1 rounded-card border hover:border-emerald transition-colors ${
                    avatarUrl === assetPath ? "border-emerald bg-emerald-light/20" : "border-sand-dark"
                  }`}
                >
                  <img src={assetPath} alt="Asset" className="h-10 w-full object-cover rounded" />
                </button>
              ))}
            </div>
          </div>

          <div className="border-t border-sand-light pt-4">
            <Field label="Upload Custom Photo" hint="Drag and drop or browse to upload custom picture. Converts to local Base64.">
              <div className="mt-1 flex flex-col items-center justify-center rounded-card border-2 border-dashed border-sand-dark/60 bg-white p-4 hover:border-emerald/50 transition-colors relative min-h-20">
                <div className="text-center">
                  <p className="text-xs text-ink font-semibold">
                    Drag & drop image here, or{" "}
                    <label className="text-emerald cursor-pointer hover:underline font-bold">
                      browse
                      <input
                        type="file"
                        accept="image/*"
                        className="hidden"
                        onChange={(e) => {
                          const file = e.target.files?.[0];
                          if (!file) return;
                          const reader = new FileReader();
                          reader.onload = (ue) => {
                            setAvatarUrl(ue.target?.result as string);
                            setAvatarModalOpen(false);
                          };
                          reader.readAsDataURL(file);
                        }}
                      />
                    </label>
                  </p>
                </div>
                <div
                  className="absolute inset-0 opacity-0 cursor-pointer"
                  onDragOver={(e) => e.preventDefault()}
                  onDrop={(e) => {
                    e.preventDefault();
                    const file = e.dataTransfer.files?.[0];
                    if (file && file.type.startsWith("image/")) {
                      const reader = new FileReader();
                      reader.onload = (ue) => {
                        setAvatarUrl(ue.target?.result as string);
                        setAvatarModalOpen(false);
                      };
                      reader.readAsDataURL(file);
                    }
                  }}
                />
              </div>
            </Field>
          </div>

          <div className="border-t border-sand-light pt-4">
            <Field label="Custom Image URL" hint="Paste any direct web link to a profile image.">
              <div className="flex gap-2">
                <Input
                  value={customAvatarInput}
                  onChange={(e) => setCustomAvatarInput(e.target.value)}
                  placeholder="https://example.com/photo.jpg"
                />
                <Button
                  onClick={() => {
                    setAvatarUrl(customAvatarInput);
                    setAvatarModalOpen(false);
                  }}
                  type="button"
                >
                  Apply
                </Button>
              </div>
            </Field>
          </div>
        </div>
      </Modal>
    </div>
  );
}

function Row({
  icon,
  label,
  children,
}: {
  icon: React.ReactNode;
  label: string;
  children: React.ReactNode;
}) {
  return (
    <div className="flex items-center justify-between rounded-card bg-sand/40 px-3 py-2 text-sm">
      <span className="flex items-center gap-2 text-muted">
        {icon}
        {label}
      </span>
      <span className="font-semibold text-ink">{children}</span>
    </div>
  );
}