"use client";

import { useState, useEffect } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { Loader2, Save, User, Lock, CheckCircle } from "lucide-react";
import { authApi } from "@/lib/api/client";
import { useAuthStore } from "@/lib/store/auth-store";
import type { User as UserType } from "@/types";

export default function SettingsPage() {
  const queryClient = useQueryClient();
  const { setUser, setAuth } = useAuthStore();

  // Profile form
  const [nameHi, setNameHi] = useState("");
  const [nameEn, setNameEn] = useState("");
  const [phone, setPhone] = useState("");
  const [designation, setDesignation] = useState("");
  const [institution, setInstitution] = useState("");
  const [department, setDepartment] = useState("");
  const [orcidId, setOrcidId] = useState("");
  const [bioHi, setBioHi] = useState("");
  const [bioEn, setBioEn] = useState("");
  const [saving, setSaving] = useState(false);
  const [saveSuccess, setSaveSuccess] = useState(false);
  const [saveError, setSaveError] = useState<string | null>(null);

  // Password form
  const [currentPassword, setCurrentPassword] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [changingPassword, setChangingPassword] = useState(false);
  const [passwordSuccess, setPasswordSuccess] = useState(false);
  const [passwordError, setPasswordError] = useState<string | null>(null);

  const { data: profile, isLoading } = useQuery<UserType>({
    queryKey: ["profile"],
    queryFn: async () => {
      const res = await authApi.me();
      return res.data;
    },
  });

  useEffect(() => {
    if (profile) {
      setNameHi(profile.nameHi || "");
      setNameEn(profile.nameEn || "");
      setPhone(profile.phone || "");
      setDesignation(profile.designation || "");
      setInstitution(profile.institution || "");
      setDepartment(profile.department || "");
      setOrcidId(profile.orcidId || "");
      setBioHi(profile.bioHi || "");
      setBioEn(profile.bioEn || "");
    }
  }, [profile]);

  const handleSaveProfile = async () => {
    setSaving(true);
    setSaveError(null);
    setSaveSuccess(false);
    try {
      const res = await authApi.updateProfile({
        nameHi, nameEn, phone: phone || null,
        designation: designation || null,
        institution: institution || null,
        department: department || null,
        orcidId: orcidId || null,
        bioHi: bioHi || null,
        bioEn: bioEn || null,
      });
      // Update auth store with new profile data
      setUser(res.data);
      // Also update localStorage
      if (typeof window !== "undefined") {
        localStorage.setItem("shodh_user", JSON.stringify(res.data));
      }
      queryClient.invalidateQueries({ queryKey: ["profile"] });
      setSaveSuccess(true);
      setTimeout(() => setSaveSuccess(false), 3000);
    } catch (err: unknown) {
      const msg = (err as { response?: { data?: { message?: string } } })?.response?.data?.message;
      setSaveError(msg || "प्रोफ़ाइल सहेजने में त्रुटि / Failed to save profile");
    }
    setSaving(false);
  };

  const handleChangePassword = async () => {
    setPasswordError(null);
    setPasswordSuccess(false);

    if (newPassword.length < 8) {
      setPasswordError("पासवर्ड कम से कम 8 अक्षर का होना चाहिए / Password must be at least 8 characters");
      return;
    }
    if (newPassword !== confirmPassword) {
      setPasswordError("पासवर्ड मेल नहीं खाते / Passwords do not match");
      return;
    }

    setChangingPassword(true);
    try {
      // Changing the password revokes every session issued before it, this one
      // included. The server hands back a replacement token; storing it is what
      // keeps the user signed in instead of being bounced to the login screen
      // the moment they succeed.
      const { data } = await authApi.changePassword({ currentPassword, newPassword });
      if (data?.token && data?.user) {
        setAuth(data.user, data.token);
      }
      setCurrentPassword("");
      setNewPassword("");
      setConfirmPassword("");
      setPasswordSuccess(true);
      setTimeout(() => setPasswordSuccess(false), 3000);
    } catch (err: unknown) {
      const msg = (err as { response?: { data?: { message?: string } } })?.response?.data?.message;
      setPasswordError(msg || "पासवर्ड बदलने में त्रुटि / Failed to change password");
    }
    setChangingPassword(false);
  };

  if (isLoading) {
    return (
      <div className="flex flex-col items-center justify-center py-20 gap-3">
        <Loader2 className="h-8 w-8 animate-spin text-indigo-500" />
        <p className="text-sm text-gray-400">लोड हो रहा है... / Loading...</p>
      </div>
    );
  }

  return (
    <div className="mx-auto max-w-3xl px-4 sm:px-6 py-8">
      <h1 className="text-2xl font-bold text-gray-900 mb-1">
        सेटिंग्स / Settings
      </h1>
      <p className="text-sm text-gray-500 mb-8">
        अपनी प्रोफ़ाइल और खाता सेटिंग्स प्रबंधित करें / Manage your profile and account settings
      </p>

      {/* Profile Section */}
      <div className="rounded-2xl border border-gray-100 bg-white p-6 shadow-sm mb-6">
        <div className="flex items-center gap-2 mb-5">
          <User className="h-5 w-5 text-indigo-600" />
          <h2 className="text-lg font-semibold text-gray-900">प्रोफ़ाइल / Profile</h2>
        </div>

        <div className="space-y-4">
          {/* Email (read-only) */}
          <div>
            <label className="block text-xs font-medium text-gray-500 mb-1">ईमेल / Email</label>
            <input
              type="email"
              value={profile?.email || ""}
              disabled
              className="w-full rounded-lg border border-gray-200 bg-gray-50 px-3 py-2 text-sm text-gray-500 cursor-not-allowed"
            />
            <p className="mt-0.5 text-[10px] text-gray-400">ईमेल बदला नहीं जा सकता / Email cannot be changed</p>
          </div>

          {/* Role (read-only) */}
          <div>
            <label className="block text-xs font-medium text-gray-500 mb-1">भूमिका / Role</label>
            <input
              type="text"
              value={profile?.role || ""}
              disabled
              className="w-full rounded-lg border border-gray-200 bg-gray-50 px-3 py-2 text-sm text-gray-500 cursor-not-allowed"
            />
          </div>

          {/* Name fields */}
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div>
              <label className="block text-xs font-medium text-gray-500 mb-1">नाम (हिन्दी) / Name (Hindi) *</label>
              <input
                type="text"
                value={nameHi}
                onChange={(e) => setNameHi(e.target.value)}
                className="w-full rounded-lg border border-gray-200 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-400"
              />
            </div>
            <div>
              <label className="block text-xs font-medium text-gray-500 mb-1">Name (English) *</label>
              <input
                type="text"
                value={nameEn}
                onChange={(e) => setNameEn(e.target.value)}
                className="w-full rounded-lg border border-gray-200 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-400"
              />
            </div>
          </div>

          {/* Phone */}
          <div>
            <label className="block text-xs font-medium text-gray-500 mb-1">फ़ोन / Phone</label>
            <input
              type="tel"
              value={phone}
              onChange={(e) => setPhone(e.target.value)}
              placeholder="9876543210"
              className="w-full rounded-lg border border-gray-200 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-400"
            />
          </div>

          {/* Professional details */}
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div>
              <label className="block text-xs font-medium text-gray-500 mb-1">पदनाम / Designation</label>
              <input
                type="text"
                value={designation}
                onChange={(e) => setDesignation(e.target.value)}
                placeholder="प्रोफेसर / Professor"
                className="w-full rounded-lg border border-gray-200 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-400"
              />
            </div>
            <div>
              <label className="block text-xs font-medium text-gray-500 mb-1">संस्थान / Institution</label>
              <input
                type="text"
                value={institution}
                onChange={(e) => setInstitution(e.target.value)}
                placeholder="विश्वविद्यालय / University"
                className="w-full rounded-lg border border-gray-200 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-400"
              />
            </div>
          </div>

          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div>
              <label className="block text-xs font-medium text-gray-500 mb-1">विभाग / Department</label>
              <input
                type="text"
                value={department}
                onChange={(e) => setDepartment(e.target.value)}
                placeholder="कंप्यूटर विज्ञान / Computer Science"
                className="w-full rounded-lg border border-gray-200 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-400"
              />
            </div>
            <div>
              <label className="block text-xs font-medium text-gray-500 mb-1">ORCID ID</label>
              <input
                type="text"
                value={orcidId}
                onChange={(e) => setOrcidId(e.target.value)}
                placeholder="0000-0002-1234-5678"
                className="w-full rounded-lg border border-gray-200 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-400"
              />
            </div>
          </div>

          {/* Bio */}
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div>
              <label className="block text-xs font-medium text-gray-500 mb-1">परिचय (हिन्दी) / Bio (Hindi)</label>
              <textarea
                rows={3}
                value={bioHi}
                onChange={(e) => setBioHi(e.target.value)}
                className="w-full rounded-lg border border-gray-200 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-400 resize-none"
              />
            </div>
            <div>
              <label className="block text-xs font-medium text-gray-500 mb-1">Bio (English)</label>
              <textarea
                rows={3}
                value={bioEn}
                onChange={(e) => setBioEn(e.target.value)}
                className="w-full rounded-lg border border-gray-200 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-400 resize-none"
              />
            </div>
          </div>

          {/* Save button & messages */}
          {saveError ? (
            <p className="text-xs text-red-600">{saveError}</p>
          ) : null}
          {saveSuccess ? (
            <p className="flex items-center gap-1 text-xs text-green-600">
              <CheckCircle className="h-3.5 w-3.5" />
              प्रोफ़ाइल सहेजी गई / Profile saved successfully
            </p>
          ) : null}
          <button
            onClick={handleSaveProfile}
            disabled={saving || !nameHi || !nameEn}
            className="flex items-center gap-2 rounded-lg bg-indigo-600 px-5 py-2.5 text-sm font-semibold text-white hover:bg-indigo-700 disabled:bg-gray-300 transition-colors"
          >
            {saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
            प्रोफ़ाइल सहेजें / Save Profile
          </button>
        </div>
      </div>

      {/* Password Section */}
      <div className="rounded-2xl border border-gray-100 bg-white p-6 shadow-sm">
        <div className="flex items-center gap-2 mb-5">
          <Lock className="h-5 w-5 text-indigo-600" />
          <h2 className="text-lg font-semibold text-gray-900">पासवर्ड बदलें / Change Password</h2>
        </div>

        <div className="space-y-4 max-w-md">
          <div>
            <label className="block text-xs font-medium text-gray-500 mb-1">वर्तमान पासवर्ड / Current Password</label>
            <input
              type="password"
              value={currentPassword}
              onChange={(e) => setCurrentPassword(e.target.value)}
              className="w-full rounded-lg border border-gray-200 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-400"
            />
          </div>
          <div>
            <label className="block text-xs font-medium text-gray-500 mb-1">नया पासवर्ड / New Password</label>
            <input
              type="password"
              value={newPassword}
              onChange={(e) => setNewPassword(e.target.value)}
              className="w-full rounded-lg border border-gray-200 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-400"
            />
            <p className="mt-0.5 text-[10px] text-gray-400">कम से कम 8 अक्षर / At least 8 characters</p>
          </div>
          <div>
            <label className="block text-xs font-medium text-gray-500 mb-1">पासवर्ड पुष्टि / Confirm Password</label>
            <input
              type="password"
              value={confirmPassword}
              onChange={(e) => setConfirmPassword(e.target.value)}
              className="w-full rounded-lg border border-gray-200 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-400"
            />
          </div>

          {passwordError ? (
            <p className="text-xs text-red-600">{passwordError}</p>
          ) : null}
          {passwordSuccess ? (
            <p className="flex items-center gap-1 text-xs text-green-600">
              <CheckCircle className="h-3.5 w-3.5" />
              पासवर्ड बदल दिया गया / Password changed successfully
            </p>
          ) : null}
          <button
            onClick={handleChangePassword}
            disabled={changingPassword || !currentPassword || !newPassword || !confirmPassword}
            className="flex items-center gap-2 rounded-lg bg-gray-800 px-5 py-2.5 text-sm font-semibold text-white hover:bg-gray-900 disabled:bg-gray-300 transition-colors"
          >
            {changingPassword ? <Loader2 className="h-4 w-4 animate-spin" /> : <Lock className="h-4 w-4" />}
            पासवर्ड बदलें / Change Password
          </button>
        </div>
      </div>
    </div>
  );
}
