"use client";

import { useState, useEffect } from "react";
import { updateSitePreferences } from "@/actions/admin/preferences";
import { Button, Card, Input } from "@/components/ui";

interface SitePreferences {
  id: string;
  houseJoinPoints: number;
  houseLeavePoints: number;
  houseCreatePoints: number;
}

interface HousePointsPreferencesProps {
  initialPreferences: SitePreferences;
}

export default function HousePointsPreferences({
  initialPreferences,
}: HousePointsPreferencesProps) {
  const [preferences, setPreferences] = useState<SitePreferences | null>(
    initialPreferences
  );
  const [isEditing, setIsEditing] = useState(false);
  const [formData, setFormData] = useState({
    houseJoinPoints: initialPreferences.houseJoinPoints.toString(),
    houseLeavePoints: initialPreferences.houseLeavePoints.toString(),
    houseCreatePoints: initialPreferences.houseCreatePoints.toString(),
  });
  const [isSaving, setIsSaving] = useState(false);

  // Synchroniser les préférences quand initialPreferences change
  useEffect(() => {
    setPreferences(initialPreferences);
    setFormData({
      houseJoinPoints: initialPreferences.houseJoinPoints.toString(),
      houseLeavePoints: initialPreferences.houseLeavePoints.toString(),
      houseCreatePoints: initialPreferences.houseCreatePoints.toString(),
    });
  }, [initialPreferences]);

  const handleEdit = () => {
    setIsEditing(true);
  };

  const handleSave = async () => {
    const joinPoints = parseInt(formData.houseJoinPoints, 10);
    const leavePoints = parseInt(formData.houseLeavePoints, 10);
    const createPoints = parseInt(formData.houseCreatePoints, 10);
    
    if (isNaN(joinPoints) || joinPoints < 0) {
      alert("Le nombre de points pour rejoindre une maison doit être un nombre positif");
      return;
    }
    
    if (isNaN(leavePoints) || leavePoints < 0) {
      alert("Le nombre de points pour quitter une maison doit être un nombre positif");
      return;
    }
    
    if (isNaN(createPoints) || createPoints < 0) {
      alert("Le nombre de points pour créer une maison doit être un nombre positif");
      return;
    }

    setIsSaving(true);
    try {
      const result = await updateSitePreferences({
        houseJoinPoints: joinPoints,
        houseLeavePoints: leavePoints,
        houseCreatePoints: createPoints,
      });

      if (result.success && result.data) {
        setPreferences(result.data);
        setFormData({
          houseJoinPoints: result.data.houseJoinPoints.toString(),
          houseLeavePoints: result.data.houseLeavePoints.toString(),
          houseCreatePoints: result.data.houseCreatePoints.toString(),
        });
        setIsEditing(false);
      } else {
        console.error("Error updating preferences:", result.error);
        alert(result.error || "Erreur lors de la mise à jour");
      }
    } catch (error) {
      console.error("Error updating preferences:", error);
      alert("Erreur lors de la mise à jour");
    } finally {
      setIsSaving(false);
    }
  };

  const handleCancel = () => {
    setIsEditing(false);
    if (preferences) {
      setFormData({
        houseJoinPoints: preferences.houseJoinPoints.toString(),
        houseLeavePoints: preferences.houseLeavePoints.toString(),
        houseCreatePoints: preferences.houseCreatePoints.toString(),
      });
    }
  };

  return (
    <Card variant="default" className="p-3 sm:p-4">
      <div className="flex flex-col sm:flex-row sm:justify-between sm:items-start gap-3 mb-4">
        <div className="min-w-0 flex-1">
          <h3 className="text-pixel-gold font-bold text-base sm:text-lg break-words">
            Points des Maisons
          </h3>
          <p className="text-gray-400 text-xs sm:text-sm">
            Nombre de points attribués ou retirés pour les actions liées aux maisons
          </p>
        </div>
        {!isEditing && (
          <Button
            onClick={handleEdit}
            variant="primary"
            size="sm"
            className="whitespace-nowrap flex-shrink-0"
          >
            Modifier
          </Button>
        )}
      </div>

      {isEditing ? (
        <div className="space-y-4">
          <div>
            <label
              htmlFor="houseJoinPoints"
              className="block text-sm font-medium text-pixel-gold mb-2"
            >
              Points pour rejoindre une maison
            </label>
            <Input
              id="houseJoinPoints"
              type="number"
              min="0"
              value={formData.houseJoinPoints}
              onChange={(e) =>
                setFormData({
                  ...formData,
                  houseJoinPoints: e.target.value,
                })
              }
              placeholder="100"
              className="w-full"
            />
            <p className="text-xs text-gray-400 mt-1">
              Les utilisateurs gagneront ce nombre de points lorsqu&apos;ils rejoignent une maison
            </p>
          </div>
          
          <div>
            <label
              htmlFor="houseLeavePoints"
              className="block text-sm font-medium text-pixel-gold mb-2"
            >
              Points retirés en quittant une maison
            </label>
            <Input
              id="houseLeavePoints"
              type="number"
              min="0"
              value={formData.houseLeavePoints}
              onChange={(e) =>
                setFormData({
                  ...formData,
                  houseLeavePoints: e.target.value,
                })
              }
              placeholder="100"
              className="w-full"
            />
            <p className="text-xs text-gray-400 mt-1">
              Les utilisateurs perdront ce nombre de points lorsqu&apos;ils quittent une maison
            </p>
          </div>
          
          <div>
            <label
              htmlFor="houseCreatePoints"
              className="block text-sm font-medium text-pixel-gold mb-2"
            >
              Points pour créer une maison
            </label>
            <Input
              id="houseCreatePoints"
              type="number"
              min="0"
              value={formData.houseCreatePoints}
              onChange={(e) =>
                setFormData({
                  ...formData,
                  houseCreatePoints: e.target.value,
                })
              }
              placeholder="100"
              className="w-full"
            />
            <p className="text-xs text-gray-400 mt-1">
              Les utilisateurs gagneront ce nombre de points lorsqu&apos;ils créent une maison
            </p>
          </div>
          
          <div className="flex flex-col sm:flex-row gap-2 pt-4">
            <Button
              onClick={handleSave}
              variant="success"
              size="md"
              disabled={isSaving}
            >
              {isSaving ? "Enregistrement..." : "Enregistrer"}
            </Button>
            <Button
              onClick={handleCancel}
              variant="secondary"
              size="md"
              disabled={isSaving}
            >
              Annuler
            </Button>
          </div>
        </div>
      ) : (
        <div className="space-y-3">
          <div className="flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-4">
            <span className="text-pixel-gold font-bold text-sm sm:text-base min-w-0 sm:min-w-[200px] flex-shrink-0">
              Points pour rejoindre:
            </span>
            <div className="flex items-center gap-2">
              <span className="text-lg sm:text-xl font-bold text-white">
                {preferences?.houseJoinPoints ?? 100}
              </span>
              <span className="text-xs sm:text-sm text-gray-400">points</span>
            </div>
          </div>
          
          <div className="flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-4">
            <span className="text-pixel-gold font-bold text-sm sm:text-base min-w-0 sm:min-w-[200px] flex-shrink-0">
              Points retirés en quittant:
            </span>
            <div className="flex items-center gap-2">
              <span className="text-lg sm:text-xl font-bold text-white">
                {preferences?.houseLeavePoints ?? 100}
              </span>
              <span className="text-xs sm:text-sm text-gray-400">points</span>
            </div>
          </div>
          
          <div className="flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-4">
            <span className="text-pixel-gold font-bold text-sm sm:text-base min-w-0 sm:min-w-[200px] flex-shrink-0">
              Points pour créer:
            </span>
            <div className="flex items-center gap-2">
              <span className="text-lg sm:text-xl font-bold text-white">
                {preferences?.houseCreatePoints ?? 100}
              </span>
              <span className="text-xs sm:text-sm text-gray-400">points</span>
            </div>
          </div>
        </div>
      )}
    </Card>
  );
}

