import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Textarea } from "@/components/ui/textarea";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
import {
  User,
  Mail,
  Phone,
  Calendar,
  Edit3,
  Save,
  X,
  Shield,
  Clock,
  ArrowLeft,
  Settings,
  KeyRound,
  ShieldCheck,
  History,
  Sparkles,
  Check,
  Loader2,
  AlertCircle,
} from "lucide-react";
import { useAuth } from "@/contexts/AuthContext";
import { useToast } from "@/hooks/use-toast";
import { useNavigate, useSearchParams } from "react-router-dom";
import { supabase } from "@/integrations/supabase/client";
import { format } from "date-fns";

interface ProfileData {
  display_name: string;
  bio: string;
  phone: string;
  avatar_url?: string;
}

export default function ProfilePage() {
  const { user, profile, refreshProfile, isAdmin } = useAuth();
  const { toast } = useToast();
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();

  const [isEditing, setIsEditing] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [activeTab, setActiveTab] = useState("profile");

  // 邮箱修改
  const [isChangingEmail, setIsChangingEmail] = useState(false);
  const [newEmail, setNewEmail] = useState("");
  const [emailLoading, setEmailLoading] = useState(false);

  const [formData, setFormData] = useState<ProfileData>({
    display_name: "",
    bio: "",
    phone: "",
    avatar_url: "",
  });

  useEffect(() => {
    const tab = searchParams.get("tab");
    if (tab && ["profile", "security", "preferences"].includes(tab)) {
      setActiveTab(tab);
    }
  }, [searchParams]);

  useEffect(() => {
    if (profile) {
      setFormData({
        display_name: profile.display_name || "",
        bio: profile.bio || "",
        phone: profile.phone || "",
        avatar_url: profile.avatar_url || "",
      });
    }
  }, [profile]);

  const handleSave = async () => {
    if (!user) return;
    setIsLoading(true);
    try {
      const { error } = await supabase
        .from("profiles")
        .update({
          display_name: formData.display_name,
          bio: formData.bio,
          phone: formData.phone,
          updated_at: new Date().toISOString(),
        })
        .eq("user_id", user.id);

      if (error) throw error;
      toast({ title: "个人资料更新成功", description: "您的个人信息已保存" });
      setIsEditing(false);
      refreshProfile();
    } catch (error: any) {
      toast({
        title: "更新失败",
        description: error.message || "请稍后重试",
        variant: "destructive",
      });
    }
    setIsLoading(false);
  };

  const handleCancel = () => {
    if (profile) {
      setFormData({
        display_name: profile.display_name || "",
        bio: profile.bio || "",
        phone: profile.phone || "",
        avatar_url: profile.avatar_url || "",
      });
    }
    setIsEditing(false);
  };

  const handleChangeEmail = async () => {
    if (!newEmail || !user) return;
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(newEmail)) {
      toast({ title: "邮箱格式不正确", description: "请输入有效的邮箱地址", variant: "destructive" });
      return;
    }
    if (newEmail === user.email) {
      toast({ title: "邮箱未改变", description: "新邮箱地址与当前邮箱相同" });
      return;
    }
    setEmailLoading(true);
    try {
      const { error } = await supabase.auth.updateUser({ email: newEmail });
      if (error) throw error;
      toast({
        title: "验证邮件已发送",
        description: `请前往 ${newEmail} 查收验证邮件，点击链接后邮箱即可生效`,
      });
      setIsChangingEmail(false);
      setNewEmail("");
    } catch (error: any) {
      toast({
        title: "修改失败",
        description: error.message || "请稍后重试",
        variant: "destructive",
      });
    }
    setEmailLoading(false);
  };

  if (!user) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center">
        <div className="text-center">
          <h2 className="text-2xl font-bold text-foreground mb-2">请先登录</h2>
          <p className="text-muted-foreground">您需要登录才能查看个人中心</p>
        </div>
      </div>
    );
  }

  const initial =
    profile?.display_name?.[0]?.toUpperCase() ||
    user?.email?.[0]?.toUpperCase() ||
    "U";

  return (
    <div className="min-h-screen bg-background">
      {/* 顶部条 */}
      <div className="border-b border-border/60 bg-background/80 backdrop-blur sticky top-0 z-10">
        <div className="container mx-auto px-4 sm:px-6 lg:px-8 h-14 flex items-center justify-between">
          <div className="flex items-center gap-3">
            <Button
              variant="ghost"
              size="sm"
              onClick={() => navigate(-1)}
              className="-ml-2"
            >
              <ArrowLeft className="h-4 w-4 mr-1.5" />
              返回
            </Button>
            <Separator orientation="vertical" className="h-5" />
            <h1 className="text-base font-semibold">个人中心</h1>
          </div>
          {isAdmin && (
            <Button
              variant="outline"
              size="sm"
              onClick={() => navigate("/admin")}
            >
              <Settings className="h-4 w-4 mr-1.5" />
              管理后台
            </Button>
          )}
        </div>
      </div>

      <div className="container mx-auto px-4 sm:px-6 lg:px-8 py-6 lg:py-10 max-w-6xl">
        <div className="grid grid-cols-1 lg:grid-cols-[320px_1fr] gap-6 lg:gap-8">
          {/* 左侧个人卡 */}
          <aside className="space-y-4">
            <Card className="overflow-hidden">
              {/* 顶部装饰渐变 */}
              <div className="h-20 bg-gradient-to-br from-primary/15 via-primary/5 to-transparent" />
              <CardContent className="-mt-12 pb-6">
                <div className="flex flex-col items-center text-center space-y-3">
                  <Avatar className="h-20 w-20 ring-4 ring-background shadow-md">
                    <AvatarFallback className="bg-primary text-primary-foreground text-xl font-semibold">
                      {initial}
                    </AvatarFallback>
                  </Avatar>
                  <div className="space-y-1">
                    <h2 className="text-lg font-semibold leading-tight">
                      {profile?.display_name || "未设置昵称"}
                    </h2>
                    <p className="text-xs text-muted-foreground truncate max-w-[240px]">
                      {user.email || user.phone || "—"}
                    </p>
                  </div>
                  <Badge variant="success" className="gap-1.5">
                    <span className="w-1.5 h-1.5 rounded-full bg-current" />
                    在线
                  </Badge>
                </div>
              </CardContent>

              <Separator />

              <CardContent className="py-4 space-y-3 text-sm">
                <div className="flex items-center justify-between">
                  <span className="text-muted-foreground">角色</span>
                  <Badge variant={isAdmin ? "default" : "secondary"}>
                    {isAdmin ? "管理员" : "用户"}
                  </Badge>
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-muted-foreground flex items-center gap-1.5">
                    <Calendar className="h-3.5 w-3.5" />
                    注册时间
                  </span>
                  <span className="font-medium text-foreground">
                    {profile?.created_at
                      ? format(new Date(profile.created_at), "yyyy-MM-dd")
                      : "—"}
                  </span>
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-muted-foreground flex items-center gap-1.5">
                    <Clock className="h-3.5 w-3.5" />
                    最后登录
                  </span>
                  <span className="font-medium text-foreground">
                    {profile?.last_login
                      ? format(new Date(profile.last_login), "MM-dd HH:mm")
                      : "未记录"}
                  </span>
                </div>
              </CardContent>
            </Card>

            {/* 快捷小贴士 */}
            <Card className="bg-muted/30 border-dashed">
              <CardContent className="py-4 flex items-start gap-3">
                <div className="p-1.5 rounded-md bg-primary/10 shrink-0">
                  <Sparkles className="h-4 w-4 text-primary" />
                </div>
                <div className="space-y-0.5">
                  <p className="text-sm font-medium">完善你的资料</p>
                  <p className="text-xs text-muted-foreground leading-relaxed">
                    设置头像、昵称与简介，让 AI 助理更懂你。
                  </p>
                </div>
              </CardContent>
            </Card>
          </aside>

          {/* 右侧内容 */}
          <main>
            <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-5">
              <TabsList className="grid w-full grid-cols-3 sm:w-auto sm:inline-flex">
                <TabsTrigger value="profile">个人信息</TabsTrigger>
                <TabsTrigger value="security">安全设置</TabsTrigger>
                <TabsTrigger value="preferences">偏好设置</TabsTrigger>
              </TabsList>

              {/* 个人信息 */}
              <TabsContent value="profile" className="mt-0">
                <Card>
                  <CardHeader className="flex flex-row items-start justify-between gap-4 space-y-0">
                    <div className="space-y-1">
                      <CardTitle className="text-lg">个人信息</CardTitle>
                      <CardDescription className="text-xs">
                        管理你的公开资料与联系方式
                      </CardDescription>
                    </div>
                    {!isEditing ? (
                      <Button onClick={() => setIsEditing(true)} variant="outline" size="sm">
                        <Edit3 className="h-3.5 w-3.5 mr-1.5" />
                        编辑
                      </Button>
                    ) : (
                      <div className="flex gap-2">
                        <Button onClick={handleSave} size="sm" disabled={isLoading}>
                          <Save className="h-3.5 w-3.5 mr-1.5" />
                          {isLoading ? "保存中..." : "保存"}
                        </Button>
                        <Button onClick={handleCancel} variant="outline" size="sm">
                          <X className="h-3.5 w-3.5 mr-1.5" />
                          取消
                        </Button>
                      </div>
                    )}
                  </CardHeader>

                  <Separator />

                  <CardContent className="pt-6 space-y-6">
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
                      <div className="space-y-1.5">
                        <Label htmlFor="display_name" className="text-xs text-muted-foreground">
                          显示名称
                        </Label>
                        <div className="relative">
                          <User className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                          <Input
                            id="display_name"
                            value={formData.display_name}
                            onChange={(e) =>
                              setFormData({ ...formData, display_name: e.target.value })
                            }
                            className="pl-9"
                            placeholder="请输入昵称"
                            disabled={!isEditing}
                          />
                        </div>
                      </div>

                      <div className="space-y-1.5">
                        <Label htmlFor="email" className="text-xs text-muted-foreground flex items-center justify-between">
                          <span>邮箱地址</span>
                          {!isChangingEmail && (
                            <Button
                              variant="link"
                              size="sm"
                              className="h-auto p-0 text-xs"
                              onClick={() => {
                                setNewEmail("");
                                setIsChangingEmail(true);
                              }}
                            >
                              修改
                            </Button>
                          )}
                        </Label>
                        {isChangingEmail ? (
                          <div className="space-y-2">
                            <div className="relative">
                              <Mail className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                              <Input
                                id="new_email"
                                type="email"
                                value={newEmail}
                                onChange={(e) => setNewEmail(e.target.value)}
                                className="pl-9"
                                placeholder="请输入新邮箱地址"
                                autoFocus
                              />
                            </div>
                            <p className="text-[11px] text-muted-foreground flex items-center gap-1">
                              <AlertCircle className="h-3 w-3" />
                              修改后需前往新邮箱验证才能生效
                            </p>
                            <div className="flex gap-2">
                              <Button size="sm" onClick={handleChangeEmail} disabled={emailLoading}>
                                {emailLoading ? (
                                  <Loader2 className="h-3.5 w-3.5 mr-1.5 animate-spin" />
                                ) : (
                                  <Check className="h-3.5 w-3.5 mr-1.5" />
                                )}
                                确认修改
                              </Button>
                              <Button
                                size="sm"
                                variant="outline"
                                onClick={() => {
                                  setIsChangingEmail(false);
                                  setNewEmail("");
                                }}
                              >
                                取消
                              </Button>
                            </div>
                          </div>
                        ) : (
                          <div className="relative">
                            <Mail className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                            <Input
                              id="email"
                              value={user.email || ""}
                              className="pl-9 bg-muted/40"
                              disabled
                            />
                          </div>
                        )}
                      </div>

                      <div className="space-y-1.5">
                        <Label htmlFor="phone" className="text-xs text-muted-foreground">
                          手机号码
                        </Label>
                        <div className="relative">
                          <Phone className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                          <Input
                            id="phone"
                            value={formData.phone}
                            onChange={(e) =>
                              setFormData({ ...formData, phone: e.target.value })
                            }
                            className="pl-9"
                            placeholder="请输入手机号码"
                            disabled={!isEditing}
                          />
                        </div>
                      </div>

                      <div className="space-y-1.5">
                        <Label className="text-xs text-muted-foreground">邮箱验证状态</Label>
                        <div className="flex items-center gap-2 h-10">
                          <Badge variant={profile?.email_verified ? "success" : "secondary"}>
                            {profile?.email_verified ? "已验证" : "未验证"}
                          </Badge>
                          {!profile?.email_verified && (
                            <Button variant="link" size="sm" className="h-auto p-0 text-xs">
                              去验证 →
                            </Button>
                          )}
                        </div>
                      </div>
                    </div>

                    <Separator />

                    <div className="space-y-1.5">
                      <Label htmlFor="bio" className="text-xs text-muted-foreground">
                        个人简介
                      </Label>
                      <Textarea
                        id="bio"
                        value={formData.bio}
                        onChange={(e) => setFormData({ ...formData, bio: e.target.value })}
                        placeholder="介绍一下您自己..."
                        className="min-h-[110px] resize-none"
                        disabled={!isEditing}
                      />
                      <p className="text-[11px] text-muted-foreground text-right">
                        {formData.bio.length} / 200
                      </p>
                    </div>
                  </CardContent>
                </Card>
              </TabsContent>

              {/* 安全设置 */}
              <TabsContent value="security" className="mt-0">
                <Card>
                  <CardHeader>
                    <CardTitle className="text-lg flex items-center gap-2">
                      <Shield className="h-4 w-4" />
                      安全设置
                    </CardTitle>
                    <CardDescription className="text-xs">
                      保护账户安全，定期检查登录与权限
                    </CardDescription>
                  </CardHeader>
                  <Separator />
                  <CardContent className="pt-6 divide-y divide-border/60">
                    <SecurityRow
                      icon={KeyRound}
                      title="密码修改"
                      desc="定期更换密码可以保护账户安全"
                      action={<Button variant="outline" size="sm">修改密码</Button>}
                    />
                    <SecurityRow
                      icon={ShieldCheck}
                      title="两步验证"
                      desc="为账户添加额外的登录验证步骤"
                      action={
                        <div className="flex items-center gap-2">
                          <Badge variant="secondary">未启用</Badge>
                          <Button variant="outline" size="sm">启用</Button>
                        </div>
                      }
                    />
                    <SecurityRow
                      icon={History}
                      title="登录记录"
                      desc="查看最近的登录设备与时间"
                      action={<Button variant="outline" size="sm">查看记录</Button>}
                    />
                  </CardContent>
                </Card>
              </TabsContent>

              {/* 偏好设置 */}
              <TabsContent value="preferences" className="mt-0">
                <Card>
                  <CardHeader>
                    <CardTitle className="text-lg">偏好设置</CardTitle>
                    <CardDescription className="text-xs">
                      个性化你的使用体验
                    </CardDescription>
                  </CardHeader>
                  <Separator />
                  <CardContent className="pt-6">
                    <Alert>
                      <AlertDescription>
                        偏好设置功能正在开发中，敬请期待...
                      </AlertDescription>
                    </Alert>
                  </CardContent>
                </Card>
              </TabsContent>
            </Tabs>
          </main>
        </div>
      </div>
    </div>
  );
}

interface SecurityRowProps {
  icon: React.ComponentType<{ className?: string }>;
  title: string;
  desc: string;
  action: React.ReactNode;
}

function SecurityRow({ icon: Icon, title, desc, action }: SecurityRowProps) {
  return (
    <div className="flex items-center justify-between gap-4 py-4 first:pt-0 last:pb-0">
      <div className="flex items-start gap-3 min-w-0">
        <div className="p-2 rounded-md bg-muted shrink-0">
          <Icon className="h-4 w-4 text-foreground/70" />
        </div>
        <div className="min-w-0">
          <p className="text-sm font-medium">{title}</p>
          <p className="text-xs text-muted-foreground mt-0.5">{desc}</p>
        </div>
      </div>
      <div className="shrink-0">{action}</div>
    </div>
  );
}
