"use client";

import * as React from "react";
import { toast } from "sonner";
import {
  Save,
  UserCircle,
  Camera,
  X,
  Mail,
  Briefcase,
  Building2,
  Shield,
  Loader2,
  Lock,
  Eye,
  EyeOff,
} from "lucide-react";

import { Header } from "@/components/layout/header";
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 { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { useUserProfile } from "@/lib/user-profile";

export default function ProfilePage() {
  const { profile, updateProfile, initials, role, isAuthenticated, loading } = useUserProfile();

  const [form, setForm] = React.useState({
    jobTitle: profile.jobTitle,
    company: profile.company,
    bio: profile.bio,
    displayName: profile.displayName,
    email: profile.email,
    avatarUrl: profile.avatarUrl,
  });
  const [dirty, setDirty] = React.useState(false);

  React.useEffect(() => {
    setForm({
      jobTitle: profile.jobTitle,
      company: profile.company,
      bio: profile.bio,
      displayName: profile.displayName,
      email: profile.email,
      avatarUrl: profile.avatarUrl,
    });
  }, [profile]);

  const handleChange = (field: string, value: string) => {
    setForm((prev) => ({ ...prev, [field]: value }));
    setDirty(true);
  };

  const [saving, setSaving] = React.useState(false);
  const [pwForm, setPwForm] = React.useState({
    currentPassword: "",
    newPassword: "",
    confirmPassword: "",
  });
  const [pwSaving, setPwSaving] = React.useState(false);
  const [showCurrentPw, setShowCurrentPw] = React.useState(false);
  const [showNewPw, setShowNewPw] = React.useState(false);

  const handlePasswordChange = async () => {
    if (pwForm.newPassword.length < 8) {
      toast.error("Password must be at least 8 characters");
      return;
    }
    if (pwForm.newPassword !== pwForm.confirmPassword) {
      toast.error("Passwords do not match");
      return;
    }
    setPwSaving(true);
    try {
      const res = await fetch("/api/auth/change-password", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          currentPassword: pwForm.currentPassword,
          newPassword: pwForm.newPassword,
        }),
      });
      const data = await res.json();
      if (!res.ok) {
        toast.error(data.error || "Failed to change password");
        return;
      }
      toast.success("Password changed successfully");
      setPwForm({ currentPassword: "", newPassword: "", confirmPassword: "" });
    } catch {
      toast.error("Failed to change password");
    } finally {
      setPwSaving(false);
    }
  };

  const handleSave = async () => {
    setSaving(true);
    try {
      await updateProfile({
        jobTitle: form.jobTitle,
        company: form.company,
        bio: form.bio,
        displayName: form.displayName,
        email: form.email,
        avatarUrl: form.avatarUrl,
      });
      setDirty(false);
      toast.success("Profile updated");
    } catch {
      toast.error("Failed to save profile");
    } finally {
      setSaving(false);
    }
  };

  const handleAvatarUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    if (!file.type.startsWith("image/")) {
      toast.error("Please select an image file");
      return;
    }

    if (file.size > 2 * 1024 * 1024) {
      toast.error("Image must be under 2 MB");
      return;
    }

    const reader = new FileReader();
    reader.onload = () => {
      handleChange("avatarUrl", reader.result as string);
    };
    reader.readAsDataURL(file);
  };

  const removeAvatar = () => {
    handleChange("avatarUrl", "");
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <Loader2 className="size-8 animate-spin text-muted-foreground" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <Header title="Profile" description="Manage your personal information" icon={UserCircle}>
        <Button className="rounded-xl" onClick={handleSave} disabled={!dirty || saving}>
          {saving ? <Loader2 className="mr-2 size-4 animate-spin" /> : <Save className="mr-2 size-4" />}
          {saving ? "Saving…" : "Save Changes"}
        </Button>
      </Header>

      {isAuthenticated && (
        <div className="flex items-center gap-2 rounded-xl border border-emerald-500/20 bg-emerald-500/5 px-4 py-3">
          <Shield className="size-4 shrink-0 text-emerald-600 dark:text-emerald-400" />
          <p className="text-sm text-emerald-700 dark:text-emerald-300">
            Signed in as <span className="font-medium">{profile.displayName || profile.email}</span>.
            Role: <Badge variant="secondary" className="ml-1 text-[10px] px-1.5 py-0">{role}</Badge>
          </p>
        </div>
      )}

      <div className="grid gap-4 sm:gap-6 grid-cols-1 lg:grid-cols-3">
        <Card variant="glass" className="lg:col-span-1">
          <CardHeader>
            <CardTitle className="text-base">Photo</CardTitle>
            <CardDescription>
              Your profile picture is visible in the header
            </CardDescription>
          </CardHeader>
          <CardContent className="flex flex-col items-center gap-4">
            <div className="relative group">
              <Avatar size="lg" className="!size-24 text-2xl">
                {form.avatarUrl && (
                  <AvatarImage src={form.avatarUrl} alt={form.displayName} />
                )}
                <AvatarFallback className="text-2xl">
                  {initials || <UserCircle className="size-10 text-muted-foreground" />}
                </AvatarFallback>
              </Avatar>
              <label className="absolute inset-0 flex cursor-pointer items-center justify-center rounded-full bg-black/40 opacity-0 transition-opacity group-hover:opacity-100">
                <Camera className="size-6 text-white" />
                <input
                  type="file"
                  accept="image/*"
                  className="hidden"
                  onChange={handleAvatarUpload}
                />
              </label>
            </div>
            <div className="flex gap-2">
              <Button
                variant="outline"
                size="sm"
                className="rounded-xl"
                onClick={() => document.querySelector<HTMLInputElement>('input[type="file"]')?.click()}
              >
                <Camera className="mr-1.5 size-3" />
                Upload
              </Button>
              {form.avatarUrl && (
                <Button
                  variant="ghost"
                  size="sm"
                  className="rounded-xl text-muted-foreground"
                  onClick={removeAvatar}
                >
                  <X className="mr-1.5 size-3" />
                  Remove
                </Button>
              )}
            </div>
            <p className="text-center text-xs text-muted-foreground">
              JPG, PNG or WebP. Max 2 MB.
            </p>
          </CardContent>
        </Card>

        <Card variant="glass" className="lg:col-span-2">
          <CardHeader>
            <CardTitle className="text-base">Personal Information</CardTitle>
            <CardDescription>
              Update your name, email, and other details
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-5">
            <div className="grid gap-4 sm:grid-cols-2">
              <div>
                <Label className="mb-1.5 flex items-center gap-1.5 text-xs font-medium text-muted-foreground">
                  <UserCircle className="size-3" />
                  Display Name
                </Label>
                <Input
                  value={form.displayName}
                  onChange={(e) => handleChange("displayName", e.target.value)}
                  placeholder="Your name"
                />
              </div>
              <div>
                <Label className="mb-1.5 flex items-center gap-1.5 text-xs font-medium text-muted-foreground">
                  <Mail className="size-3" />
                  Email
                </Label>
                <Input
                  type="email"
                  value={form.email}
                  onChange={(e) => handleChange("email", e.target.value)}
                  placeholder="you@example.com"
                  readOnly
                  className="bg-muted/40 cursor-default"
                />
              </div>
            </div>

            <div className="grid gap-4 sm:grid-cols-2">
              <div>
                <Label className="mb-1.5 flex items-center gap-1.5 text-xs font-medium text-muted-foreground">
                  <Briefcase className="size-3" />
                  Job Title
                </Label>
                <Input
                  value={form.jobTitle}
                  onChange={(e) => handleChange("jobTitle", e.target.value)}
                  placeholder="e.g. Project Manager"
                />
              </div>
              <div>
                <Label className="mb-1.5 flex items-center gap-1.5 text-xs font-medium text-muted-foreground">
                  <Building2 className="size-3" />
                  Company
                </Label>
                <Input
                  value={form.company}
                  onChange={(e) => handleChange("company", e.target.value)}
                  placeholder="e.g. Echo Labs"
                />
              </div>
            </div>

            <div>
              <Label className="mb-1.5 block text-xs font-medium text-muted-foreground">
                Bio
              </Label>
              <Textarea
                value={form.bio}
                onChange={(e) => handleChange("bio", e.target.value)}
                placeholder="Tell us a little about yourself..."
                className="min-h-24 resize-none"
              />
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Security — Change Password */}
      <Card variant="glass">
        <CardHeader>
          <CardTitle className="flex items-center gap-2 text-base">
            <Lock className="size-4" />
            Security
          </CardTitle>
          <CardDescription>
            {profile.hasPassword
              ? "Change your account password"
              : "Set a password for your account"}
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
            {profile.hasPassword && (
              <div>
                <Label className="mb-1.5 block text-xs font-medium text-muted-foreground">
                  Current Password
                </Label>
                <div className="relative">
                  <Input
                    type={showCurrentPw ? "text" : "password"}
                    value={pwForm.currentPassword}
                    onChange={(e) =>
                      setPwForm((p) => ({ ...p, currentPassword: e.target.value }))
                    }
                    placeholder="••••••••"
                  />
                  <button
                    type="button"
                    className="absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
                    onClick={() => setShowCurrentPw(!showCurrentPw)}
                    tabIndex={-1}
                  >
                    {showCurrentPw ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
                  </button>
                </div>
              </div>
            )}
            <div>
              <Label className="mb-1.5 block text-xs font-medium text-muted-foreground">
                New Password
              </Label>
              <div className="relative">
                <Input
                  type={showNewPw ? "text" : "password"}
                  value={pwForm.newPassword}
                  onChange={(e) =>
                    setPwForm((p) => ({ ...p, newPassword: e.target.value }))
                  }
                  placeholder="At least 8 characters"
                />
                <button
                  type="button"
                  className="absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
                  onClick={() => setShowNewPw(!showNewPw)}
                  tabIndex={-1}
                >
                  {showNewPw ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
                </button>
              </div>
            </div>
            <div>
              <Label className="mb-1.5 block text-xs font-medium text-muted-foreground">
                Confirm New Password
              </Label>
              <Input
                type="password"
                value={pwForm.confirmPassword}
                onChange={(e) =>
                  setPwForm((p) => ({ ...p, confirmPassword: e.target.value }))
                }
                placeholder="Repeat new password"
              />
            </div>
          </div>

          {pwForm.newPassword.length > 0 && pwForm.newPassword.length < 8 && (
            <p className="text-xs text-amber-600 dark:text-amber-400">
              Password must be at least 8 characters
            </p>
          )}
          {pwForm.confirmPassword.length > 0 &&
            pwForm.newPassword !== pwForm.confirmPassword && (
              <p className="text-xs text-red-600 dark:text-red-400">
                Passwords do not match
              </p>
            )}

          <Button
            variant="outline"
            className="rounded-xl"
            onClick={handlePasswordChange}
            disabled={
              pwSaving ||
              pwForm.newPassword.length < 8 ||
              pwForm.newPassword !== pwForm.confirmPassword ||
              (profile.hasPassword && !pwForm.currentPassword)
            }
          >
            {pwSaving ? (
              <Loader2 className="mr-2 size-4 animate-spin" />
            ) : (
              <Lock className="mr-2 size-4" />
            )}
            {profile.hasPassword ? "Change Password" : "Set Password"}
          </Button>
        </CardContent>
      </Card>
    </div>
  );
}
