"use client";

import { useState, useEffect } from "react";
import { useUser } from "@/hooks/useUser";

const TIMEZONES = [
  { value: "America/New_York", label: "Eastern Time (ET)" },
  { value: "America/Chicago", label: "Central Time (CT)" },
  { value: "America/Denver", label: "Mountain Time (MT)" },
  { value: "America/Los_Angeles", label: "Pacific Time (PT)" },
];

const NOTIFICATION_METHODS = [
  { value: "imessage", label: "iMessage" },
  { value: "web", label: "Web" },
  { value: "both", label: "Both" },
];

interface ProfileData {
  displayName: string;
  phone: string;
  timezone: string;
  notificationMethod: string;
  quietHoursStart: string;
  quietHoursEnd: string;
}

function getStorageKey(email: string) {
  return `profile-${email}`;
}

function loadProfile(email: string, fallbackName: string): ProfileData {
  try {
    const raw = localStorage.getItem(getStorageKey(email));
    if (raw) return JSON.parse(raw);
  } catch {}
  return {
    displayName: fallbackName,
    phone: "",
    timezone: "America/New_York",
    notificationMethod: "web",
    quietHoursStart: "22:00",
    quietHoursEnd: "07:00",
  };
}

export function ProfileView() {
  const { email, name } = useUser();
  const displayEmail = email || "";
  const fallbackName = name || (email ? email.split("@")[0] : "");

  const [form, setForm] = useState<ProfileData>({
    displayName: fallbackName,
    phone: "",
    timezone: "America/New_York",
    notificationMethod: "web",
    quietHoursStart: "22:00",
    quietHoursEnd: "07:00",
  });
  const [saved, setSaved] = useState(false);
  const [loaded, setLoaded] = useState(false);

  useEffect(() => {
    if (!loaded && displayEmail) {
      setForm(loadProfile(displayEmail, fallbackName));
      setLoaded(true);
    }
  }, [displayEmail, fallbackName, loaded]);

  function handleChange(field: keyof ProfileData, value: string) {
    setForm((prev) => ({ ...prev, [field]: value }));
    setSaved(false);
  }

  function handleSave() {
    try {
      localStorage.setItem(getStorageKey(displayEmail), JSON.stringify(form));
    } catch {}
    setSaved(true);
    setTimeout(() => setSaved(false), 2000);
  }

  // Build initials for the large avatar
  const avatarSource = form.displayName || displayEmail || "U";
  const initials = avatarSource
    .split(/[@.\s]/)
    .filter(Boolean)
    .slice(0, 2)
    .map((s: string) => s[0].toUpperCase())
    .join("");

  return (
    <div className="flex h-full flex-col overflow-y-auto bg-white dark:bg-zinc-950">
      <div className="mx-auto w-full max-w-xl px-6 py-10">
        {/* Page heading */}
        <h1 className="mb-8 text-xl font-semibold text-zinc-900 dark:text-zinc-100">Profile</h1>

        {/* Large avatar */}
        <div className="mb-8 flex justify-center">
          <div className="group relative h-32 w-32 cursor-pointer">
            <div className="flex h-32 w-32 items-center justify-center rounded-full bg-zinc-200 text-3xl font-semibold text-zinc-700 dark:bg-zinc-700 dark:text-zinc-200">
              {initials}
            </div>
            {/* Hover overlay — placeholder for future avatar picker */}
            <div className="absolute inset-0 flex items-center justify-center rounded-full bg-black/40 opacity-0 transition-opacity group-hover:opacity-100">
              <span className="text-xs font-medium text-white">Change avatar</span>
            </div>
          </div>
        </div>

        {/* Form */}
        <div className="space-y-5">
          {/* Display Name */}
          <div>
            <label className="mb-1.5 block text-sm font-medium text-zinc-700 dark:text-zinc-300">
              Display Name
            </label>
            <input
              type="text"
              value={form.displayName}
              onChange={(e) => handleChange("displayName", e.target.value)}
              className="w-full rounded-lg border border-zinc-200 bg-white px-3 py-2 text-sm text-zinc-900 outline-none transition focus:border-zinc-400 focus:ring-1 focus:ring-zinc-400 dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-100 dark:focus:border-zinc-500 dark:focus:ring-zinc-500"
            />
          </div>

          {/* Email — read-only */}
          <div>
            <label className="mb-1.5 block text-sm font-medium text-zinc-700 dark:text-zinc-300">
              Email
            </label>
            <p className="rounded-lg border border-zinc-200 bg-zinc-50 px-3 py-2 text-sm text-zinc-500 dark:border-zinc-700 dark:bg-zinc-900/50 dark:text-zinc-400">
              {displayEmail || "—"}
            </p>
          </div>

          {/* Phone */}
          <div>
            <label className="mb-1.5 block text-sm font-medium text-zinc-700 dark:text-zinc-300">
              Phone Number
            </label>
            <input
              type="tel"
              value={form.phone}
              onChange={(e) => handleChange("phone", e.target.value)}
              placeholder="+1 (555) 000-0000"
              className="w-full rounded-lg border border-zinc-200 bg-white px-3 py-2 text-sm text-zinc-900 outline-none transition placeholder:text-zinc-400 focus:border-zinc-400 focus:ring-1 focus:ring-zinc-400 dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-100 dark:placeholder:text-zinc-600 dark:focus:border-zinc-500 dark:focus:ring-zinc-500"
            />
          </div>

          {/* Timezone */}
          <div>
            <label className="mb-1.5 block text-sm font-medium text-zinc-700 dark:text-zinc-300">
              Timezone
            </label>
            <select
              value={form.timezone}
              onChange={(e) => handleChange("timezone", e.target.value)}
              className="w-full rounded-lg border border-zinc-200 bg-white px-3 py-2 text-sm text-zinc-900 outline-none transition focus:border-zinc-400 focus:ring-1 focus:ring-zinc-400 dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-100 dark:focus:border-zinc-500 dark:focus:ring-zinc-500"
            >
              {TIMEZONES.map((tz) => (
                <option key={tz.value} value={tz.value}>
                  {tz.label}
                </option>
              ))}
            </select>
          </div>

          {/* Notification Method */}
          <div>
            <label className="mb-2 block text-sm font-medium text-zinc-700 dark:text-zinc-300">
              Preferred Notification Method
            </label>
            <div className="flex flex-wrap gap-4">
              {NOTIFICATION_METHODS.map((method) => (
                <label key={method.value} className="flex cursor-pointer items-center gap-2">
                  <input
                    type="radio"
                    name="notificationMethod"
                    value={method.value}
                    checked={form.notificationMethod === method.value}
                    onChange={(e) => handleChange("notificationMethod", e.target.value)}
                    className="h-4 w-4 accent-zinc-600 dark:accent-zinc-400"
                  />
                  <span className="text-sm text-zinc-700 dark:text-zinc-300">{method.label}</span>
                </label>
              ))}
            </div>
          </div>

          {/* Quiet Hours */}
          <div>
            <label className="mb-2 block text-sm font-medium text-zinc-700 dark:text-zinc-300">
              Quiet Hours
            </label>
            <div className="flex items-center gap-3">
              <div className="flex flex-1 flex-col gap-1">
                <span className="text-xs text-zinc-500 dark:text-zinc-400">Start</span>
                <input
                  type="time"
                  value={form.quietHoursStart}
                  onChange={(e) => handleChange("quietHoursStart", e.target.value)}
                  className="w-full rounded-lg border border-zinc-200 bg-white px-3 py-2 text-sm text-zinc-900 outline-none transition focus:border-zinc-400 focus:ring-1 focus:ring-zinc-400 dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-100 dark:focus:border-zinc-500 dark:focus:ring-zinc-500"
                />
              </div>
              <span className="mt-4 text-sm text-zinc-400 dark:text-zinc-500">to</span>
              <div className="flex flex-1 flex-col gap-1">
                <span className="text-xs text-zinc-500 dark:text-zinc-400">End</span>
                <input
                  type="time"
                  value={form.quietHoursEnd}
                  onChange={(e) => handleChange("quietHoursEnd", e.target.value)}
                  className="w-full rounded-lg border border-zinc-200 bg-white px-3 py-2 text-sm text-zinc-900 outline-none transition focus:border-zinc-400 focus:ring-1 focus:ring-zinc-400 dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-100 dark:focus:border-zinc-500 dark:focus:ring-zinc-500"
                />
              </div>
            </div>
          </div>
        </div>

        {/* Save button */}
        <div className="mt-8 flex items-center gap-3">
          <button
            onClick={handleSave}
            className="rounded-lg bg-zinc-900 px-4 py-2 text-sm font-medium text-white transition hover:bg-zinc-700 active:scale-95 dark:bg-zinc-100 dark:text-zinc-900 dark:hover:bg-zinc-300"
          >
            Save Profile
          </button>
          {saved && (
            <span className="text-sm font-medium text-green-600 dark:text-green-400">Saved!</span>
          )}
        </div>

        {/* Placeholder sections */}
        <div className="mt-10 space-y-4">
          <div className="rounded-xl border-2 border-dashed border-zinc-200 p-6 dark:border-zinc-800">
            <h2 className="mb-1 text-sm font-semibold text-zinc-700 dark:text-zinc-300">
              Favorites
            </h2>
            <p className="text-sm text-zinc-400 dark:text-zinc-500">Coming soon</p>
          </div>

          <div className="rounded-xl border-2 border-dashed border-zinc-200 p-6 dark:border-zinc-800">
            <h2 className="mb-1 text-sm font-semibold text-zinc-700 dark:text-zinc-300">
              Social Links
            </h2>
            <p className="text-sm text-zinc-400 dark:text-zinc-500">Coming soon</p>
          </div>
        </div>
      </div>
    </div>
  );
}
