import { useState } from "react";
import { useAuth } from "@/context/AuthContext";
import { Navigate } from "react-router-dom";
import { FaUser, FaEnvelope, FaPhone, FaMapMarkerAlt, FaCheckCircle, FaSpinner } from "react-icons/fa";
import { apiAccountUsersPartialUpdate } from "@/api/generated/private/account/account";

export default function AccountSettings() {
  const { user, isAuthenticated, isLoading: authLoading, refreshUser } = useAuth();
  
  const [formData, setFormData] = useState({
    first_name: user?.first_name || "",
    last_name: user?.last_name || "",
    phone_number: user?.phone_number || "",
    city: user?.city || "",
    street: user?.street || "",
    postal_code: user?.postal_code || "",
  });
  
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState(false);

  if (authLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <FaSpinner className="text-blue-500 text-5xl animate-spin" />
      </div>
    );
  }

  if (!isAuthenticated) {
    return <Navigate to="/login" replace />;
  }

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setFormData(prev => ({
      ...prev,
      [e.target.name]: e.target.value
    }));
  };

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError("");
    setSuccess(false);
    setIsLoading(true);

    try {
      if (!user?.id) throw new Error("User ID not found");
      
      await apiAccountUsersPartialUpdate(user.id, formData);
      await refreshUser();
      setSuccess(true);
      setTimeout(() => setSuccess(false), 3000);
    } catch (err: any) {
      const errorMessage = err.response?.data?.error || err.message || "Nepodařilo se uložit změny";
      setError(errorMessage);
    } finally {
      setIsLoading(false);
    }
  }

  return (
    <div className="min-h-screen bg-gray-50 py-12 px-4">
      <div className="max-w-3xl mx-auto">
        <div className="bg-white rounded-lg shadow-lg p-8">
          <h1 className="text-3xl font-bold text-gray-800 mb-2">Nastavení účtu</h1>
          <p className="text-gray-600 mb-8">Upravte své osobní údaje</p>

          {/* User info (read-only) */}
          <div className="mb-8 p-4 bg-blue-50 border border-blue-200 rounded-lg">
            <h2 className="font-semibold text-gray-800 mb-2">Informace o účtu</h2>
            <div className="space-y-1 text-sm">
              <p><strong>Username:</strong> {user?.username}</p>
              <p><strong>Email:</strong> {user?.email}</p>
              <p><strong>Role:</strong> {user?.role || "user"}</p>
              <p><strong>Email ověřen:</strong> {user?.email_verified ? "✅ Ano" : "❌ Ne"}</p>
            </div>
          </div>

          {success && (
            <div className="mb-6 p-4 bg-green-50 border border-green-200 text-green-700 rounded-lg flex items-center gap-2">
              <FaCheckCircle />
              <span>Změny byly úspěšně uloženy!</span>
            </div>
          )}

          {error && (
            <div className="mb-6 p-4 bg-red-50 border border-red-200 text-red-700 rounded-lg">
              <strong>Chyba:</strong> {error}
            </div>
          )}

          <form onSubmit={handleSubmit} className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <label className="block mb-2 font-medium text-gray-700 flex items-center gap-2">
                  <FaUser className="text-gray-500" />
                  Jméno
                </label>
                <input
                  type="text"
                  name="first_name"
                  value={formData.first_name}
                  onChange={handleChange}
                  placeholder="Jan"
                  className="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition"
                  disabled={isLoading}
                  maxLength={150}
                />
              </div>

              <div>
                <label className="block mb-2 font-medium text-gray-700 flex items-center gap-2">
                  <FaUser className="text-gray-500" />
                  Příjmení
                </label>
                <input
                  type="text"
                  name="last_name"
                  value={formData.last_name}
                  onChange={handleChange}
                  placeholder="Novák"
                  className="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition"
                  disabled={isLoading}
                  maxLength={150}
                />
              </div>
            </div>

            <div>
              <label className="block mb-2 font-medium text-gray-700 flex items-center gap-2">
                <FaPhone className="text-gray-500" />
                Telefon
              </label>
              <input
                type="tel"
                name="phone_number"
                value={formData.phone_number}
                onChange={handleChange}
                placeholder="+420123456789"
                className="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition"
                disabled={isLoading}
                pattern="^\+?\d{9,15}$"
                maxLength={16}
              />
              <p className="text-xs text-gray-500 mt-1">Formát: +420123456789</p>
            </div>

            <div className="border-t pt-6">
              <h3 className="font-semibold text-gray-800 mb-4 flex items-center gap-2">
                <FaMapMarkerAlt className="text-gray-500" />
                Adresa
              </h3>
              
              <div className="space-y-4">
                <div>
                  <label className="block mb-2 font-medium text-gray-700">Město</label>
                  <input
                    type="text"
                    name="city"
                    value={formData.city}
                    onChange={handleChange}
                    placeholder="Praha"
                    className="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition"
                    disabled={isLoading}
                    maxLength={100}
                  />
                </div>

                <div>
                  <label className="block mb-2 font-medium text-gray-700">Ulice a číslo popisné</label>
                  <input
                    type="text"
                    name="street"
                    value={formData.street}
                    onChange={handleChange}
                    placeholder="Václavské náměstí 1"
                    className="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition"
                    disabled={isLoading}
                    maxLength={200}
                  />
                </div>

                <div>
                  <label className="block mb-2 font-medium text-gray-700">PSČ</label>
                  <input
                    type="text"
                    name="postal_code"
                    value={formData.postal_code}
                    onChange={handleChange}
                    placeholder="11000"
                    className="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition"
                    disabled={isLoading}
                    pattern="^\d{5}$"
                    maxLength={5}
                  />
                  <p className="text-xs text-gray-500 mt-1">5 číslic bez mezery</p>
                </div>
              </div>
            </div>

            <div className="flex gap-4 pt-4">
              <button
                type="submit"
                disabled={isLoading}
                className="flex-1 bg-blue-600 text-white py-3 rounded-lg font-semibold hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed transition flex items-center justify-center gap-2"
              >
                {isLoading ? (
                  <>
                    <FaSpinner className="animate-spin" />
                    Ukládání...
                  </>
                ) : (
                  "Uložit změny"
                )}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
}