"use client";

import * as React from "react";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { AuthSession } from "@/types";
import { formatDateID } from "@/lib/utils";
import {
  User,
  Mail,
  Phone,
  MapPin,
  Lock,
  KeyRound,
  ShieldCheck,
  CheckCircle2,
  AlertCircle,
  Save,
} from "lucide-react";

interface ProfileClientProps {
  currentUser: AuthSession;
}

export function ProfileClient({ currentUser }: ProfileClientProps) {
  const [profile, setProfile] = React.useState<any>(null);
  const [loading, setLoading] = React.useState(true);

  // Form states
  const [email, setEmail] = React.useState("");
  const [phone, setPhone] = React.useState("");
  const [address, setAddress] = React.useState("");
  const [savingInfo, setSavingInfo] = React.useState(false);
  const [infoSuccess, setInfoSuccess] = React.useState("");
  const [infoError, setInfoError] = React.useState("");

  // Password states
  const [currentPassword, setCurrentPassword] = React.useState("");
  const [newPassword, setNewPassword] = React.useState("");
  const [confirmPassword, setConfirmPassword] = React.useState("");
  const [savingPassword, setSavingPassword] = React.useState(false);
  const [passwordSuccess, setPasswordSuccess] = React.useState("");
  const [passwordError, setPasswordError] = React.useState("");

  const fetchProfile = React.useCallback(async () => {
    try {
      setLoading(true);
      const res = await fetch("/api/profile");
      const data = await res.json();
      if (data.success) {
        setProfile(data.data);
        setEmail(data.data.email || "");
        if (data.data.teacher) {
          setPhone(data.data.teacher.phone || "");
          setAddress(data.data.teacher.address || "");
        } else if (data.data.student) {
          setPhone(data.data.student.phone || "");
          setAddress(data.data.student.address || "");
        }
      }
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  }, []);

  React.useEffect(() => {
    fetchProfile();
  }, [fetchProfile]);

  const handleUpdateInfo = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      setSavingInfo(true);
      setInfoSuccess("");
      setInfoError("");

      const res = await fetch("/api/profile", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, phone, address }),
      });

      const data = await res.json();
      if (data.success) {
        setInfoSuccess("Informasi profil dan kontak berhasil disimpan!");
        fetchProfile();
      } else {
        setInfoError(data.error || "Gagal memperbarui profil.");
      }
    } catch (err) {
      setInfoError("Terjadi gangguan jaringan.");
    } finally {
      setSavingInfo(false);
    }
  };

  const handleChangePassword = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!currentPassword || !newPassword) {
      setPasswordError("Password saat ini dan password baru wajib diisi.");
      return;
    }

    if (newPassword.length < 6) {
      setPasswordError("Password baru minimal 6 karakter.");
      return;
    }

    if (newPassword !== confirmPassword) {
      setPasswordError("Konfirmasi password baru tidak cocok.");
      return;
    }

    try {
      setSavingPassword(true);
      setPasswordSuccess("");
      setPasswordError("");

      const res = await fetch("/api/profile", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ currentPassword, newPassword }),
      });

      const data = await res.json();
      if (data.success) {
        setPasswordSuccess("Kata sandi berhasil diubah! Gunakan kata sandi baru untuk login selanjutnya.");
        setCurrentPassword("");
        setNewPassword("");
        setConfirmPassword("");
      } else {
        setPasswordError(data.error || "Gagal mengubah kata sandi.");
      }
    } catch (err) {
      setPasswordError("Terjadi gangguan jaringan.");
    } finally {
      setSavingPassword(false);
    }
  };

  if (loading) {
    return <div className="p-12 text-center text-slate-400 text-xs">Memuat data profil...</div>;
  }

  const roleName =
    currentUser.role === "ADMIN"
      ? "Administrator Sekolah"
      : currentUser.role === "TEACHER"
      ? currentUser.isHomeroom
        ? "Guru Mata Pelajaran & Wali Kelas"
        : "Guru Mata Pelajaran"
      : `Peserta Didik (${currentUser.className || "X.1"})`;

  const identifier =
    profile?.teacher?.nip || profile?.student?.nis || profile?.username;

  return (
    <div className="space-y-6">
      {/* Identity Card */}
      <Card>
        <CardContent className="p-6">
          <div className="flex flex-col sm:flex-row items-center sm:items-start gap-5">
            <div className="h-20 w-20 rounded-2xl bg-gradient-to-tr from-blue-700 to-indigo-600 text-white font-extrabold text-2xl flex items-center justify-center shadow-lg shadow-blue-500/20 shrink-0">
              {currentUser.fullName.substring(0, 2).toUpperCase()}
            </div>

            <div className="flex-1 text-center sm:text-left space-y-1">
              <div className="flex flex-col sm:flex-row sm:items-center gap-2">
                <h3 className="text-xl font-bold text-slate-900">
                  {currentUser.fullName}
                </h3>
                <Badge variant="info" className="self-center sm:self-auto text-xs">
                  {roleName}
                </Badge>
              </div>

              <p className="text-xs text-slate-500 font-mono">
                Nomor Identitas (NIP / NIS): <strong>{identifier}</strong>
              </p>

              <div className="flex flex-wrap items-center justify-center sm:justify-start gap-4 pt-2 text-xs text-slate-500">
                <span className="flex items-center gap-1.5">
                  <User className="h-3.5 w-3.5 text-slate-400" />
                  Username: <strong className="font-mono text-slate-700">@{currentUser.username}</strong>
                </span>
                <span className="flex items-center gap-1.5">
                  <ShieldCheck className="h-3.5 w-3.5 text-emerald-500" />
                  Status: <strong className="text-emerald-700">Aktif Terverifikasi</strong>
                </span>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Contact Info Form */}
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-base flex items-center gap-2">
              <User className="h-4 w-4 text-blue-600" />
              Kontak & Alamat Domisili
            </CardTitle>
            <p className="text-xs text-slate-500">
              Perbarui alamat surat elektronik dan nomor telepon yang dapat dihubungi.
            </p>
          </CardHeader>
          <CardContent>
            <form onSubmit={handleUpdateInfo} className="space-y-4 text-xs">
              {infoSuccess && (
                <div className="p-3 bg-emerald-50 border border-emerald-200 text-emerald-700 rounded-lg flex items-center gap-2">
                  <CheckCircle2 className="h-4 w-4 shrink-0" />
                  <span>{infoSuccess}</span>
                </div>
              )}
              {infoError && (
                <div className="p-3 bg-rose-50 border border-rose-200 text-rose-700 rounded-lg flex items-center gap-2">
                  <AlertCircle className="h-4 w-4 shrink-0" />
                  <span>{infoError}</span>
                </div>
              )}

              <div>
                <label className="block font-semibold text-slate-700 mb-1">
                  Alamat Email (Pos-el)
                </label>
                <div className="relative">
                  <Mail className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
                  <Input
                    type="email"
                    placeholder="nama@sman3oku.sch.id"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    className="pl-9 text-xs"
                  />
                </div>
              </div>

              <div>
                <label className="block font-semibold text-slate-700 mb-1">
                  Nomor WhatsApp / Telepon
                </label>
                <div className="relative">
                  <Phone className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
                  <Input
                    placeholder="081234567890"
                    value={phone}
                    onChange={(e) => setPhone(e.target.value)}
                    className="pl-9 text-xs"
                  />
                </div>
              </div>

              <div>
                <label className="block font-semibold text-slate-700 mb-1">
                  Alamat Rumah Lengkap
                </label>
                <div className="relative">
                  <Textarea
                    placeholder="Jl. Merdeka No. 45 Baturaja Timur..."
                    value={address}
                    onChange={(e) => setAddress(e.target.value)}
                    rows={3}
                    className="text-xs"
                  />
                </div>
              </div>

              <div className="pt-2 flex justify-end">
                <Button
                  type="submit"
                  size="sm"
                  disabled={savingInfo}
                  className="bg-blue-600 hover:bg-blue-700"
                >
                  <Save className="h-3.5 w-3.5 mr-1.5" />
                  {savingInfo ? "Menyimpan..." : "Simpan Perubahan Kontak"}
                </Button>
              </div>
            </form>
          </CardContent>
        </Card>

        {/* Change Password Form */}
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-base flex items-center gap-2">
              <Lock className="h-4 w-4 text-blue-600" />
              Keamanan & Ganti Kata Sandi
            </CardTitle>
            <p className="text-xs text-slate-500">
              Gunakan kombinasi minimal 6 karakter untuk menjaga keamanan akun Anda.
            </p>
          </CardHeader>
          <CardContent>
            <form onSubmit={handleChangePassword} className="space-y-4 text-xs">
              {passwordSuccess && (
                <div className="p-3 bg-emerald-50 border border-emerald-200 text-emerald-700 rounded-lg flex items-center gap-2">
                  <CheckCircle2 className="h-4 w-4 shrink-0" />
                  <span>{passwordSuccess}</span>
                </div>
              )}
              {passwordError && (
                <div className="p-3 bg-rose-50 border border-rose-200 text-rose-700 rounded-lg flex items-center gap-2">
                  <AlertCircle className="h-4 w-4 shrink-0" />
                  <span>{passwordError}</span>
                </div>
              )}

              <div>
                <label className="block font-semibold text-slate-700 mb-1">
                  Kata Sandi Saat Ini <span className="text-rose-500">*</span>
                </label>
                <div className="relative">
                  <KeyRound className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
                  <Input
                    type="password"
                    placeholder="Masukkan kata sandi lama Anda"
                    value={currentPassword}
                    onChange={(e) => setCurrentPassword(e.target.value)}
                    required
                    className="pl-9 text-xs"
                  />
                </div>
              </div>

              <div>
                <label className="block font-semibold text-slate-700 mb-1">
                  Kata Sandi Baru <span className="text-rose-500">*</span>
                </label>
                <div className="relative">
                  <Lock className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
                  <Input
                    type="password"
                    placeholder="Minimal 6 karakter"
                    value={newPassword}
                    onChange={(e) => setNewPassword(e.target.value)}
                    required
                    className="pl-9 text-xs"
                  />
                </div>
              </div>

              <div>
                <label className="block font-semibold text-slate-700 mb-1">
                  Konfirmasi Kata Sandi Baru <span className="text-rose-500">*</span>
                </label>
                <div className="relative">
                  <Lock className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
                  <Input
                    type="password"
                    placeholder="Ulangi kata sandi baru"
                    value={confirmPassword}
                    onChange={(e) => setConfirmPassword(e.target.value)}
                    required
                    className="pl-9 text-xs"
                  />
                </div>
              </div>

              <div className="pt-2 flex justify-end">
                <Button
                  type="submit"
                  size="sm"
                  disabled={savingPassword}
                  className="bg-blue-600 hover:bg-blue-700"
                >
                  <KeyRound className="h-3.5 w-3.5 mr-1.5" />
                  {savingPassword ? "Memproses..." : "Perbarui Kata Sandi"}
                </Button>
              </div>
            </form>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
