"use client";

import { useState } from "react";
import { useAuth } from "@/contexts/auth-context";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { toast } from "sonner";
import { Loader2, Lock } from "lucide-react";
import { SiswaProfileForm } from "./_components/siswa-profile-form";

const PasswordSchema = z
  .object({
    currentPassword: z.string().min(1, "Password saat ini dibutuhkan"),
    newPassword: z.string().min(6, "Password baru minimal 6 karakter"),
    confirmPassword: z.string().min(1, "Konfirmasi password dibutuhkan"),
  })
  .refine((data) => data.newPassword === data.confirmPassword, {
    message: "Password tidak cocok",
    path: ["confirmPassword"],
  });

type PasswordFormData = z.infer<typeof PasswordSchema>;

export default function ProfilePage() {
  const { user } = useAuth();
  const [isSubmitting, setIsSubmitting] = useState(false);

  const {
    register,
    handleSubmit,
    formState: { errors },
    reset,
  } = useForm<PasswordFormData>({
    resolver: zodResolver(PasswordSchema),
  });

  const onChangePassword = async (data: PasswordFormData) => {
    setIsSubmitting(true);
    try {
      const res = await fetch("/api/auth/change-password", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data),
      });
      const json = await res.json();

      if (!res.ok) throw new Error(json.message || "Gagal mengubah password");

      toast.success("Password berhasil diubah");
      reset();
    } catch (error) {
      toast.error(error instanceof Error ? error.message : "Terjadi kesalahan");
    } finally {
      setIsSubmitting(false);
    }
  };

  if (!user) return null; // Should be handled by layout/sidebar

  return (
    <div className="container max-w-4xl space-y-6 p-5">
      <h1 className="text-3xl font-bold">Profil Saya</h1>

      <div className="grid gap-6 md:grid-cols-3">
        {/* Profile Card */}
        <Card className="md:col-span-1">
          <CardHeader className="text-center">
            <div className="mx-auto mb-4">
              <Avatar className="h-24 w-24">
                <AvatarImage src={"/avatars/default.jpg"} />
                <AvatarFallback className="text-2xl">{user.name?.charAt(0).toUpperCase()}</AvatarFallback>
              </Avatar>
            </div>
            <CardTitle>{user.name}</CardTitle>
            <CardDescription className="uppercase">{user.role}</CardDescription>
            <div className="mt-2">
              <Badge variant={user.role === "ADMIN" ? "default" : "secondary"}>{user.role}</Badge>
            </div>
          </CardHeader>
          <CardContent className="space-y-4 text-sm">
            <div className="grid gap-1">
              <Label className="text-muted-foreground">Username</Label>
              <div className="bg-muted rounded p-2 font-medium">{user.username}</div>
            </div>
            {user.email && (
              <div className="grid gap-1">
                <Label className="text-muted-foreground">Email</Label>
                <div className="bg-muted rounded p-2 font-medium">{user.email}</div>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Change Password */}
        <Card className="md:col-span-2">
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Lock className="h-5 w-5" />
              Ganti Password
            </CardTitle>
            <CardDescription>Perbarui password akun Anda secara berkala untuk keamanan.</CardDescription>
          </CardHeader>
          <CardContent>
            <form onSubmit={handleSubmit(onChangePassword)} className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="current">Password Saat Ini</Label>
                <Input id="current" type="password" {...register("currentPassword")} />
                {errors.currentPassword && <p className="text-destructive text-sm">{errors.currentPassword.message}</p>}
              </div>
              <div className="grid gap-4 md:grid-cols-2">
                <div className="space-y-2">
                  <Label htmlFor="new">Password Baru</Label>
                  <Input id="new" type="password" {...register("newPassword")} />
                  {errors.newPassword && <p className="text-destructive text-sm">{errors.newPassword.message}</p>}
                </div>
                <div className="space-y-2">
                  <Label htmlFor="confirm">Konfirmasi Password</Label>
                  <Input id="confirm" type="password" {...register("confirmPassword")} />
                  {errors.confirmPassword && (
                    <p className="text-destructive text-sm">{errors.confirmPassword.message}</p>
                  )}
                </div>
              </div>
              <div className="flex justify-end">
                <Button type="submit" disabled={isSubmitting}>
                  {isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                  Simpan Password
                </Button>
              </div>
            </form>
          </CardContent>
        </Card>

        {/* Siswa Data */}
        {user.role === "SISWA" && <SiswaProfileForm />}
      </div>
    </div>
  );
}
