"use client";

import { useState } from "react";
import {
  Mail, Calendar, Shield, Edit3,
  Check, X, LogOut, Bell, Mic,
  Video, Clock, ChevronRight,
} from "lucide-react";
import { useRouter } from "next/navigation";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Separator } from "@/components/ui/separator";
import { Badge } from "@/components/ui/badge";
import { PageHeader } from "@/components/ui/page-components";
import { SimpleTooltip } from "@/components/ui/tooltip";
import { useUserStore, useMeetingsStore, useToast } from "@/store";
import { getInitials } from "@/lib/utils";

export default function ProfilePage() {
  const router = useRouter();
  const { email, displayName, joinedAt, setDisplayName, clearUser } = useUserStore();
  const meetings = useMeetingsStore((s) => s.meetings);
  const { success, error } = useToast();

  const [editingName, setEditingName] = useState(false);
  const [nameInput, setNameInput] = useState(displayName);

  const initials = displayName ? getInitials(displayName) : getInitials(email);
  const completedMeetings = meetings.filter((m) => m.status === "completed").length;
  const totalHours = Math.floor(meetings.reduce((acc, m) => acc + m.duration, 0) / 3600);
  const joinedDate = joinedAt
    ? new Intl.DateTimeFormat("en-US", { month: "long", day: "numeric", year: "numeric" }).format(new Date(joinedAt))
    : "—";

  const handleSaveName = () => {
    const trimmed = nameInput.trim();
    if (trimmed.length < 2) {
      error("Invalid name", "Name must be at least 2 characters.");
      return;
    }
    setDisplayName(trimmed);
    setEditingName(false);
    success("Name updated", "Your display name has been saved.");
  };

  const handleSignOut = () => {
    clearUser();
    sessionStorage.removeItem("auth_token");
    sessionStorage.removeItem("auth_email");
    document.cookie = "auth_token=; path=/; max-age=0";
    router.push("/login");
  };

  return (
    <div className="max-w-4xl space-y-6">
      <PageHeader
        title="My Profile"
        description="View and manage your account information"
      />

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">

        {/* ── Left column ── */}
        <div className="space-y-4">
          <Card>
            <CardContent className="pt-6 pb-6 flex flex-col items-center text-center gap-4">
	              <SimpleTooltip content="Your profile picture, generated from your initials">
	                <div className="relative">
	                  <Avatar className="h-20 w-20">
	                    <AvatarFallback className="bg-gradient-to-br from-blue-500 to-indigo-600 text-white text-2xl font-bold">
	                      {initials}
	                    </AvatarFallback>
	                  </Avatar>
	                  <div className="absolute bottom-0.5 right-0.5 h-5 w-5 rounded-full bg-green-500 border-2 border-white" />
	                </div>
	              </SimpleTooltip>

              <div className="space-y-1">
                <h2 className="text-base font-bold text-gray-900">{displayName || "User"}</h2>
                <p className="text-xs text-gray-500 break-all">{email}</p>
              </div>

              <Separator className="w-full" />

              <div className="w-full grid grid-cols-3 gap-2">
	                {[
	                  { icon: Video, value: meetings.length,  label: "Meetings", tooltip: "Total meetings recorded" },
	                  { icon: Check, value: completedMeetings, label: "Done", tooltip: "Completed meetings" },
	                  { icon: Clock, value: totalHours,        label: "Hours", tooltip: "Total recorded hours" },
	                ].map(({ icon: Icon, value, label, tooltip }) => (
	                  <SimpleTooltip key={label} content={tooltip}>
		                    <div className="flex flex-col items-center gap-1 rounded-lg bg-gray-50 py-3 cursor-default">
	                      <Icon className="h-4 w-4 text-blue-600" />
	                      <span className="text-lg font-bold text-gray-900">{value}</span>
	                      <span className="text-[10px] text-gray-500">{label}</span>
	                    </div>
	                  </SimpleTooltip>
	                ))}
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="py-2">
	              <SimpleTooltip content="Sign out of your account">
	                <button
	                  onClick={handleSignOut}
	                  className="w-full flex items-center gap-3 rounded-lg px-3 py-2.5 text-red-600 hover:bg-red-50 transition-colors"
	                >
	                  <LogOut className="h-4 w-4 shrink-0" />
	                  <span className="text-sm font-medium">Sign out</span>
	                </button>
	              </SimpleTooltip>
            </CardContent>
          </Card>
        </div>

        {/* ── Right column ── */}
        <div className="lg:col-span-2 space-y-4">
          <Card>
            <CardHeader>
              <CardTitle className="text-base">Account Information</CardTitle>
              <CardDescription>Your personal details from Google sign-in</CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">

              {/* Display name */}
              <div className="space-y-1.5">
                <Label>Display Name</Label>
                {editingName ? (
                  <div className="flex items-center gap-2">
                    <Input
                      value={nameInput}
                      onChange={(e) => setNameInput(e.target.value)}
                      onKeyDown={(e) => {
                        if (e.key === "Enter") handleSaveName();
                        if (e.key === "Escape") { setNameInput(displayName); setEditingName(false); }
                      }}
                      autoFocus maxLength={50} placeholder="Enter your name"
                    />
	                    <SimpleTooltip content="Save changes">
	                      <Button size="sm" onClick={handleSaveName} disabled={nameInput.trim().length < 2}>
	                        <Check className="h-4 w-4" />
	                      </Button>
	                    </SimpleTooltip>
	                    <SimpleTooltip content="Cancel editing">
	                      <Button size="sm" variant="outline" onClick={() => { setNameInput(displayName); setEditingName(false); }}>
	                        <X className="h-4 w-4" />
	                      </Button>
	                    </SimpleTooltip>
                  </div>
                ) : (
                  <div className="flex items-center justify-between rounded-lg border border-gray-200 bg-white px-4 py-2.5 group hover:border-blue-300 transition-colors">
                    <span className="text-sm text-gray-900">{displayName || "—"}</span>
	                    <SimpleTooltip content="Edit display name">
	                      <button
	                        onClick={() => { setEditingName(true); setNameInput(displayName); }}
	                        className="flex items-center gap-1 text-xs text-gray-400 hover:text-blue-600 transition-colors opacity-0 group-hover:opacity-100"
	                      >
	                        <Edit3 className="h-3.5 w-3.5" /> Edit
	                      </button>
	                    </SimpleTooltip>
                  </div>
                )}
              </div>

              {/* Email */}
              <div className="space-y-1.5">
                <Label>Email Address</Label>
                <div className="flex items-center gap-3 rounded-lg border border-gray-200 bg-gray-50 px-4 py-2.5">
	                  <SimpleTooltip content="Email address from your Google account">
	                    <Mail className="h-4 w-4 text-gray-400 shrink-0" />
	                  </SimpleTooltip>
	                  <span className="text-sm text-gray-900 flex-1 truncate">{email || "—"}</span>
	                  <SimpleTooltip content="Email address verified">
	                    <Badge variant="success" className="text-[10px] shrink-0">Verified</Badge>
	                  </SimpleTooltip>
                </div>
              </div>

              {/* Member since */}
              <div className="space-y-1.5">
                <Label>Member Since</Label>
                <div className="flex items-center gap-3 rounded-lg border border-gray-200 bg-gray-50 px-4 py-2.5">
	                  <SimpleTooltip content="Account creation date">
	                    <Calendar className="h-4 w-4 text-gray-400 shrink-0" />
	                  </SimpleTooltip>
                  <span className="text-sm text-gray-900">{joinedDate}</span>
                </div>
              </div>

              {/* Sign-in method */}
              <div className="space-y-1.5">
                <Label>Sign-in Method</Label>
                <div className="flex items-center gap-3 rounded-lg border border-gray-200 bg-gray-50 px-4 py-2.5">
                  <svg viewBox="0 0 24 24" className="h-4 w-4 shrink-0">
                    <path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" fill="#4285F4" />
                    <path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853" />
                    <path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l3.66-2.84z" fill="#FBBC05" />
                    <path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335" />
                  </svg>
                  <span className="text-sm text-gray-900 flex-1">Google Account</span>
	                  <SimpleTooltip content="Secure Google account authentication">
	                    <Shield className="h-4 w-4 text-green-500" />
	                  </SimpleTooltip>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Quick settings */}
          <Card>
            <CardHeader>
              <CardTitle className="text-base">Quick Settings</CardTitle>
              <CardDescription>Jump to frequently used settings</CardDescription>
            </CardHeader>
            <CardContent className="space-y-1 p-2">
              {[
                { icon: Bell, label: "Notification preferences", desc: "Manage alerts and reminders" },
                { icon: Mic,  label: "Transcription settings",   desc: "Language, speaker ID, auto-summary" },
              ].map(({ icon: Icon, label, desc }) => (
                <button
                  key={label}
                  onClick={() => router.push("/settings")}
                  className="w-full flex items-center gap-3 rounded-lg px-4 py-3 hover:bg-gray-50 transition-colors text-left group"
                >
                  <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-blue-50">
                    <Icon className="h-4 w-4 text-blue-600" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-medium text-gray-900">{label}</p>
                    <p className="text-xs text-gray-500 mt-0.5">{desc}</p>
                  </div>
                  <ChevronRight className="h-4 w-4 text-gray-400 group-hover:text-gray-600 transition-colors" />
                </button>
              ))}
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}
