"use client";

import { useState, useRef } from "react";
import { useQuery, useMutation } from "@tanstack/react-query";
import { Camera, User, Key, Shield } from "lucide-react";
import { usersApi } from "@/lib/api";
import { useAuthStore } from "@/store/authStore";
import { PageHeader, Spinner } from "@/components/ui";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import toast from "react-hot-toast";

const profileSchema = z.object({
  full_name: z.string().min(2, "En az 2 karakter.").optional(),
  username: z.string().min(3, "En az 3 karakter.").optional(),
});

const passwordSchema = z.object({
  current_password: z.string().min(1, "Mevcut şifre zorunlu."),
  new_password: z.string().min(8, "En az 8 karakter."),
  confirm_password: z.string(),
}).refine((d) => d.new_password === d.confirm_password, {
  message: "Şifreler eşleşmiyor.",
  path: ["confirm_password"],
});

type ProfileForm = z.infer<typeof profileSchema>;
type PasswordForm = z.infer<typeof passwordSchema>;

export default function ProfilPage() {
  const { user, updateUser } = useAuthStore();
  const fileRef = useRef<HTMLInputElement>(null);
  const [avatarPreview, setAvatarPreview] = useState<string | null>(null);

  const profileForm = useForm<ProfileForm>({
    resolver: zodResolver(profileSchema),
    defaultValues: { full_name: user?.full_name || "", username: user?.username || "" },
  });

  const passwordForm = useForm<PasswordForm>({
    resolver: zodResolver(passwordSchema),
  });

  // Profil güncelleme
  const profileMutation = useMutation({
    mutationFn: (data: ProfileForm) => usersApi.updateMe(data),
    onSuccess: (updatedUser) => {
      updateUser(updatedUser);
      toast.success("Profil güncellendi.");
    },
    onError: (err: any) => toast.error(err?.response?.data?.detail || "Güncelleme başarısız."),
  });

  // Şifre değiştirme
  const passwordMutation = useMutation({
    mutationFn: (data: PasswordForm) =>
      usersApi.updatePassword(data.current_password, data.new_password),
    onSuccess: () => {
      toast.success("Şifre başarıyla değiştirildi.");
      passwordForm.reset();
    },
    onError: (err: any) => toast.error(err?.response?.data?.detail || "Şifre değiştirilemedi."),
  });

  // Avatar yükleme
  const avatarMutation = useMutation({
    mutationFn: (file: File) => usersApi.uploadAvatar(file),
    onSuccess: (updatedUser) => {
      updateUser(updatedUser);
      toast.success("Profil fotoğrafı güncellendi.");
      setAvatarPreview(null);
    },
    onError: () => toast.error("Fotoğraf yüklenemedi."),
  });

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    if (file.size > 5 * 1024 * 1024) {
      toast.error("Dosya boyutu 5 MB'ı geçemez.");
      return;
    }
    const reader = new FileReader();
    reader.onloadend = () => setAvatarPreview(reader.result as string);
    reader.readAsDataURL(file);
    avatarMutation.mutate(file);
  };

  const avatarSrc = avatarPreview || user?.avatar_url || null;

  return (
    <div className="space-y-6 animate-fade-in max-w-2xl">
      <PageHeader title="Profilim" subtitle="Hesap bilgilerinizi yönetin" />

      {/* Avatar Bölümü */}
      <div className="kaplan-card">
        <div className="flex items-center gap-5">
          <div className="relative">
            <div className="w-20 h-20 rounded-full bg-brand-600/20 border-2 border-brand-600/30 flex items-center justify-center overflow-hidden">
              {avatarSrc ? (
                <img src={avatarSrc} alt="Profil" className="w-full h-full object-cover" />
              ) : (
                <User size={32} className="text-brand-400" />
              )}
            </div>
            <button
              onClick={() => fileRef.current?.click()}
              className="absolute -bottom-1 -right-1 w-7 h-7 bg-brand-600 hover:bg-brand-700 rounded-full flex items-center justify-center transition-colors"
              disabled={avatarMutation.isPending}
            >
              {avatarMutation.isPending ? <Spinner size={12} /> : <Camera size={12} className="text-white" />}
            </button>
            <input
              ref={fileRef}
              type="file"
              accept="image/jpeg,image/png,image/webp"
              onChange={handleFileChange}
              className="sr-only"
            />
          </div>
          <div>
            <p className="font-semibold text-surface-100 text-lg">
              {user?.full_name || user?.username}
            </p>
            <p className="text-sm text-surface-500">{user?.email}</p>
            <div className="flex items-center gap-2 mt-2">
              <Shield size={12} className="text-brand-400" />
              <span className="text-xs text-brand-400 capitalize">
                {user?.role === "admin" ? "Yönetici" : "Kullanıcı"}
              </span>
            </div>
          </div>
        </div>
      </div>

      {/* Profil Bilgileri */}
      <div className="kaplan-card">
        <h3 className="text-sm font-semibold text-surface-100 mb-5 flex items-center gap-2">
          <User size={16} className="text-surface-400" /> Profil Bilgileri
        </h3>
        <form onSubmit={profileForm.handleSubmit((d) => profileMutation.mutate(d))} className="space-y-4">
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="form-label">Ad Soyad</label>
              <input {...profileForm.register("full_name")} className="kaplan-input" />
              {profileForm.formState.errors.full_name && (
                <p className="text-xs text-red-400 mt-1">{profileForm.formState.errors.full_name.message}</p>
              )}
            </div>
            <div>
              <label className="form-label">Kullanıcı Adı</label>
              <input {...profileForm.register("username")} className="kaplan-input" />
              {profileForm.formState.errors.username && (
                <p className="text-xs text-red-400 mt-1">{profileForm.formState.errors.username.message}</p>
              )}
            </div>
          </div>
          <div>
            <label className="form-label">E-posta</label>
            <input value={user?.email || ""} disabled className="kaplan-input opacity-50 cursor-not-allowed" />
            <p className="text-xs text-surface-600 mt-1">E-posta adresi değiştirilemez.</p>
          </div>
          <div className="flex justify-end">
            <button type="submit" disabled={profileMutation.isPending} className="btn-primary">
              {profileMutation.isPending && <Spinner size={14} />} Değişiklikleri Kaydet
            </button>
          </div>
        </form>
      </div>

      {/* Şifre Değiştirme */}
      <div className="kaplan-card">
        <h3 className="text-sm font-semibold text-surface-100 mb-5 flex items-center gap-2">
          <Key size={16} className="text-surface-400" /> Şifre Değiştir
        </h3>
        <form onSubmit={passwordForm.handleSubmit((d) => passwordMutation.mutate(d))} className="space-y-4">
          <div>
            <label className="form-label">Mevcut Şifre</label>
            <input {...passwordForm.register("current_password")} type="password" className="kaplan-input" />
            {passwordForm.formState.errors.current_password && (
              <p className="text-xs text-red-400 mt-1">{passwordForm.formState.errors.current_password.message}</p>
            )}
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="form-label">Yeni Şifre</label>
              <input {...passwordForm.register("new_password")} type="password" className="kaplan-input" />
              {passwordForm.formState.errors.new_password && (
                <p className="text-xs text-red-400 mt-1">{passwordForm.formState.errors.new_password.message}</p>
              )}
            </div>
            <div>
              <label className="form-label">Yeni Şifre Tekrar</label>
              <input {...passwordForm.register("confirm_password")} type="password" className="kaplan-input" />
              {passwordForm.formState.errors.confirm_password && (
                <p className="text-xs text-red-400 mt-1">{passwordForm.formState.errors.confirm_password.message}</p>
              )}
            </div>
          </div>
          <div className="flex justify-end">
            <button type="submit" disabled={passwordMutation.isPending} className="btn-primary">
              {passwordMutation.isPending && <Spinner size={14} />} Şifremi Güncelle
            </button>
          </div>
        </form>
      </div>

      {/* Hesap Bilgileri */}
      <div className="kaplan-card">
        <h3 className="text-sm font-semibold text-surface-100 mb-4">Hesap Bilgileri</h3>
        <div className="grid grid-cols-2 gap-4 text-sm">
          <div>
            <span className="text-surface-500">Hesap ID</span>
            <p className="text-surface-300 font-mono">#{user?.id}</p>
          </div>
          <div>
            <span className="text-surface-500">Hesap Rolü</span>
            <p className="text-surface-300">{user?.role === "admin" ? "Yönetici" : "Kullanıcı"}</p>
          </div>
          <div>
            <span className="text-surface-500">Kayıt Tarihi</span>
            <p className="text-surface-300">
              {user?.created_at ? new Date(user.created_at).toLocaleDateString("tr-TR") : "—"}
            </p>
          </div>
          <div>
            <span className="text-surface-500">Hesap Durumu</span>
            <span className="badge badge-green ml-0">Aktif</span>
          </div>
        </div>
      </div>
    </div>
  );
}
