"use client";

import { useEffect, useState, useCallback } from "react";
import { useSearchParams } 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 { useToast } from "@/components/ui/Toast";
import { formatDate } from "@/lib/format";
import { UserCircle, Award, CalendarDays, GraduationCap, Calendar, CheckCircle2, XCircle, BotMessageSquare } from "lucide-react";

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

type GoogleToken = {
  volunteer_id: string;
  email: string | null;
  connected_at: string;
};

type TelegramConn = {
  volunteer_id: string;
  username: string | null;
  connected_at: string;
};

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

  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [profile, setProfile] = useState<Profile | null>(null);
  const [googleToken, setGoogleToken] = useState<GoogleToken | null>(null);
  const [telegramConn, setTelegramConn] = useState<TelegramConn | null>(null);

  const [fullName, setFullName] = useState("");
  const [matricNo, setMatricNo] = useState("");
  const [phone, setPhone] = useState("");

  const load = useCallback(async () => {
    const { data: u } = await supabase.auth.getUser();
    if (!u.user) return;
    const [prof, gt, tg] = await Promise.all([
      supabase
        .from("profiles")
        .select("id, full_name, matric_no, email, phone, role, total_merit, created_at")
        .eq("id", u.user.id)
        .single(),
      supabase
        .from("google_tokens")
        .select("volunteer_id, email, connected_at")
        .eq("volunteer_id", u.user.id)
        .maybeSingle(),
      supabase
        .from("telegram_connections")
        .select("volunteer_id, username, connected_at")
        .eq("volunteer_id", u.user.id)
        .maybeSingle(),
    ]);
    if (prof.data) {
      const p = prof.data as Profile;
      setProfile(p);
      setFullName(p.full_name ?? "");
      setMatricNo(p.matric_no ?? "");
      setPhone(p.phone ?? "");
    }
    setGoogleToken((gt.data as GoogleToken) ?? null);
    setTelegramConn((tg.data as TelegramConn) ?? null);
    setLoading(false);
  }, [supabase]);

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

  // Handle Google OAuth redirect result
  useEffect(() => {
    const google = searchParams.get("google");
    if (google === "connected") {
      notify("Google Calendar connected successfully!");
      load();
    } else if (google === "denied") {
      notify("Google Calendar connection was cancelled.", "error");
    } else if (google === "error") {
      notify("Something went wrong connecting Google Calendar.", "error");
    }
  }, [searchParams, notify, load]);

  async function save(e: React.FormEvent) {
    e.preventDefault();
    if (!profile) return;
    if (!fullName.trim()) return notify("Full name cannot be empty.", "error");
    setSaving(true);
    const { error } = await supabase
      .from("profiles")
      .update({
        full_name: fullName.trim(),
        matric_no: matricNo.trim() || null,
        phone: phone.trim() || null,
      })
      .eq("id", profile.id);
    setSaving(false);
    if (error) return notify(error.message, "error");
    notify("Profile updated.");
    load();
  }

  async function disconnectGoogle() {
    if (!profile) return;
    const { error } = await supabase
      .from("google_tokens")
      .delete()
      .eq("volunteer_id", profile.id);
    if (error) return notify(error.message, "error");
    setGoogleToken(null);
    notify("Google Calendar disconnected.");
  }

  async function disconnectTelegram() {
    if (!profile) return;
    const { error } = await supabase
      .from("telegram_connections")
      .delete()
      .eq("volunteer_id", profile.id);
    if (error) return notify(error.message, "error");
    setTelegramConn(null);
    notify("Telegram disconnected.");
  }

  // Bot username — update this to match your bot
  const telegramBotUsername = "PusatIslamUPSI_bot";

  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 || "V")
    .split(" ")
    .map((n) => n[0])
    .slice(0, 2)
    .join("")
    .toUpperCase();

  const dirty =
    fullName !== (profile.full_name ?? "") ||
    matricNo !== (profile.matric_no ?? "") ||
    phone !== (profile.phone ?? "");

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-extrabold text-ink">My Profile</h1>
        <p className="text-sm text-muted">View and update your volunteer account details.</p>
      </div>

      <div className="grid gap-6 lg:grid-cols-3">
        {/* Summary card */}
        <Card className="lg:col-span-1">
          <div className="flex flex-col items-center p-6 text-center">
            <div className="flex h-20 w-20 items-center justify-center rounded-full bg-emerald text-2xl font-bold text-white">
              {initials}
            </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={<GraduationCap size={16} className="text-emerald" />} label="Matric no.">
                {profile.matric_no || "—"}
              </Row>
              <Row icon={<Award size={16} className="text-teal" />} label="Total merit">
                {profile.total_merit} pts
              </Row>
              <Row icon={<CalendarDays size={16} className="text-muted" />} label="Member since">
                {formatDate(profile.created_at)}
              </Row>
            </div>
          </div>
        </Card>

        {/* Edit form + Google Calendar */}
        <div className="space-y-6 lg:col-span-2">
          <Card>
            <CardHeader title="Edit 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>
              <Field label="Matric no.">
                <Input
                  value={matricNo}
                  onChange={(e) => setMatricNo(e.target.value)}
                  placeholder="D20231100000"
                />
              </Field>
              <Field label="Phone" hint="Used for WhatsApp reminders.">
                <Input
                  value={phone}
                  onChange={(e) => setPhone(e.target.value)}
                  placeholder="012-3456789"
                />
              </Field>
              <Field label="Email" hint="Email is tied to your login and cannot be changed here.">
                <Input value={profile.email} disabled className="bg-sand/50" />
              </Field>
              <div className="flex justify-end gap-2 pt-2">
                <Button
                  type="button"
                  variant="secondary"
                  disabled={!dirty || saving}
                  onClick={() => {
                    setFullName(profile.full_name ?? "");
                    setMatricNo(profile.matric_no ?? "");
                    setPhone(profile.phone ?? "");
                  }}
                >
                  Reset
                </Button>
                <Button type="submit" disabled={!dirty || saving}>
                  {saving ? "Saving…" : "Save changes"}
                </Button>
              </div>
            </form>
          </Card>

          {/* Google Calendar connection */}
          <Card>
            <CardHeader title="Google Calendar" />
            <div className="p-5">
              {googleToken ? (
                <div className="space-y-4">
                  <div className="flex items-center gap-3 rounded-card bg-emerald-light/50 border border-emerald/20 px-4 py-3">
                    <CheckCircle2 size={20} className="text-emerald shrink-0" />
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-semibold text-ink">Connected</p>
                      <p className="text-xs text-muted truncate">
                        {googleToken.email ?? "Google account"} · since {formatDate(googleToken.connected_at)}
                      </p>
                    </div>
                  </div>
                  <p className="text-sm text-muted">
                    Program reminders will be added directly to your Google Calendar. You'll see
                    them in your calendar app automatically.
                  </p>
                  <Button variant="secondary" size="sm" onClick={disconnectGoogle}>
                    <XCircle size={14} /> Disconnect
                  </Button>
                </div>
              ) : (
                <div className="space-y-4">
                  <div className="flex items-center gap-3 rounded-card bg-sand/60 px-4 py-3">
                    <Calendar size={20} className="text-muted shrink-0" />
                    <div>
                      <p className="text-sm font-semibold text-ink">Not connected</p>
                      <p className="text-xs text-muted">
                        Connect your Google account so program reminders appear directly in your
                        personal calendar.
                      </p>
                    </div>
                  </div>
                  <Button size="sm" onClick={() => (window.location.href = "/api/auth/google")}>
                    <Calendar size={14} /> Connect Google Calendar
                  </Button>
                </div>
              )}
            </div>
          </Card>

          {/* Telegram connection */}
          <Card>
            <CardHeader title="Telegram Reminders" />
            <div className="p-5">
              {telegramConn ? (
                <div className="space-y-4">
                  <div className="flex items-center gap-3 rounded-card bg-blue-50 border border-blue-200/50 px-4 py-3">
                    <CheckCircle2 size={20} className="text-blue-500 shrink-0" />
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-semibold text-ink">Connected</p>
                      <p className="text-xs text-muted truncate">
                        {telegramConn.username ? `@${telegramConn.username}` : "Telegram"} · since {formatDate(telegramConn.connected_at)}
                      </p>
                    </div>
                  </div>
                  <p className="text-sm text-muted">
                    You'll receive program reminders directly on Telegram.
                  </p>
                  <Button variant="secondary" size="sm" onClick={disconnectTelegram}>
                    <XCircle size={14} /> Disconnect
                  </Button>
                </div>
              ) : (
                <div className="space-y-4">
                  <div className="flex items-center gap-3 rounded-card bg-sand/60 px-4 py-3">
                    <BotMessageSquare size={20} className="text-muted shrink-0" />
                    <div>
                      <p className="text-sm font-semibold text-ink">Not connected</p>
                      <p className="text-xs text-muted">
                        Connect Telegram to receive reminders directly on your phone.
                      </p>
                    </div>
                  </div>
                  <div className="space-y-2">
                    <Button
                      size="sm"
                      onClick={() =>
                        window.open(
                          `https://t.me/${telegramBotUsername}?start=${profile.id}`,
                          "_blank"
                        )
                      }
                    >
                      <BotMessageSquare size={14} /> Connect Telegram
                    </Button>
                    <div className="rounded-card bg-sand/40 px-3 py-2">
                      <p className="text-xs text-muted mb-1">
                        Already chatted with the bot before? Open <b>@{telegramBotUsername}</b> on Telegram and paste this ID:
                      </p>
                      <div className="flex items-center gap-2">
                        <code className="flex-1 rounded bg-white px-2 py-1 text-xs font-mono text-ink border border-sand-dark/40 select-all">
                          {profile.id}
                        </code>
                        <button
                          type="button"
                          onClick={() => {
                            navigator.clipboard.writeText(profile.id);
                            notify("Volunteer ID copied!");
                          }}
                          className="text-xs font-semibold text-emerald hover:underline"
                        >
                          Copy
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              )}
            </div>
          </Card>
        </div>
      </div>
    </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>
  );
}
