import React, { useEffect, useMemo, useState } from "react";
import { createPortal } from "react-dom";
import { motion, AnimatePresence } from "framer-motion";
import {
  X,
  Save,
  Server,
  Link,
  Key,
  Database,
  Building2,
  Loader2,
  Eye,
  EyeOff,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { Progress } from "@/components/ui/Progress";
import { Section } from "../ui/Section";
import { InputField } from "../ui/InputValidator";
import z from "zod";
import { useForm, Controller, type SubmitHandler } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { Gateways, GatewaysRequest } from "@/types/gateways";
import { toast } from "../ui/use-toast";
import { useAppDispatch } from "@/store/hooks";
import { addGateways } from "@/store/features/gateways/thunk";

// ============================================
// SCHÉMA DE VALIDATION DU FORMULAIRE
// ============================================

const gatewaySchema = z.object({
  name: z.string().min(1, "Le nom est requis").max(100, "100 caractères maximum"),
  description: z.string().max(500, "500 caractères maximum").nullable().optional(),
  gateway_url: z
    .string()
    .min(1, "L'URL est requise")
    .url("Format URL invalide (ex: https://exemple.com)"),
  token_preview: z.string().min(1, "Le token est requis"),
  sage_database: z.string().nullable().optional(),
  sage_company: z.string().nullable().optional(),
  is_active: z.boolean().default(true),
  is_default: z.boolean().default(false),
});

type GatewayFormData = z.infer<typeof gatewaySchema>;

// ============================================
// PROPS INTERFACE
// ============================================

interface ModalGatewayProps {
  open: boolean;
  onClose: () => void;
  title?: string;
  editing?: Gateways | null;
}

// ============================================
// COMPOSANT PRINCIPAL
// ============================================

export function ModalGateway({
  open,
  onClose,
  title,
  editing,
}: ModalGatewayProps) {
  const [completion, setCompletion] = useState(0);
  const [showToken, setShowToken] = useState(false);
  const dispatch = useAppDispatch();
  const isEditing = !!editing;
  
  const {
    control,
    handleSubmit,
    watch,
    reset,
    formState: { errors, isSubmitting },
  } = useForm<GatewayFormData>({
    resolver: zodResolver(gatewaySchema),
    mode: "onChange",
    defaultValues: {
      name: "",
      description: "",
      gateway_url: "",
      token_preview: "",
      sage_database: "",
      sage_company: "",
      is_active: true,
      is_default: false,
    },
  });

  const formValues = watch();

  // Reset form when modal opens/closes or editing changes
  useEffect(() => {
    if (!open) return;
    if (editing) {
      reset({
        name: editing.name || "",
        description: editing.description || "",
        gateway_url: editing.gateway_url || "",
        token_preview: editing.token_preview || "",
        sage_database: editing.sage_database || "",
        sage_company: editing.sage_company || "",
        is_active: editing.is_active ?? true,
        is_default: editing.is_default ?? false,
      });
    } else {
      reset({
        name: "",
        description: "",
        gateway_url: "",
        token_preview: "",
        sage_database: "",
        sage_company: "",
        is_active: true,
        is_default: false,
      });
    }
    setShowToken(false);
  }, [open, editing, reset]);

  // Calculate completion percentage
  useEffect(() => {
    const requiredFields: (keyof GatewayFormData)[] = ["name", "gateway_url", "token_preview"];
    const optionalFields: (keyof GatewayFormData)[] = ["description", "sage_database", "sage_company"];
    
    const filledRequired = requiredFields.filter((f) => !!formValues[f]);
    const filledOptional = optionalFields.filter((f) => !!formValues[f]);
    
    const requiredWeight = 0.7;
    const optionalWeight = 0.3;
    
    const requiredCompletion = (filledRequired.length / requiredFields.length) * requiredWeight;
    const optionalCompletion = (filledOptional.length / optionalFields.length) * optionalWeight;
    
    setCompletion(Math.round((requiredCompletion + optionalCompletion) * 100));
  }, [formValues]);

  const canSave = useMemo(() => {
    return !!formValues.name && !!formValues.gateway_url && !!formValues.token_preview;
  }, [formValues.name, formValues.gateway_url, formValues.token_preview]);

  // Submit handler
  const handleFormSubmit: SubmitHandler<GatewayFormData> = async (data) => {
    const payload: GatewaysRequest = {
      name: data.name,
      description: data.description || null,
      gateway_url: data.gateway_url,
      gateway_token: data.token_preview,
      is_active: data.is_active,
      is_default: data.is_default,
    };

   try {
        const rep = await dispatch(addGateways(payload)).unwrap() as Gateways;
        console.log("rep : ",rep);
        
        onClose
        toast({
            title: "Entreprise bien créé !",
            description: `Votre nouvelle entreprise a été créé avec succès.`,
            className: "bg-green-500 text-white border-green-600"
        });
   } catch (error) {
        toast({
            title: "Erreur du creation d'entreprise !",
            className: "bg-red-500 text-white border-green-600"
        });
        onClose
   }
    
    // await onSave(payload, isEditing, editing?.id);
  };

  // Debug: Show validation errors
  const onError = (validationErrors: typeof errors) => {
    console.log("Erreurs de validation:", validationErrors);
  };

  if (!open) return null;

  return createPortal(
    <AnimatePresence>
      {open && (
        <div className="absolute inset-0 z-[9999] overflow-hidden">
          {/* Backdrop */}
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            onClick={onClose}
            className="absolute inset-0 bg-black/40 backdrop-blur-sm"
          />

          {/* Modal Panel */}
          <motion.div
            initial={{ x: "100%" }}
            animate={{ x: 0 }}
            exit={{ x: "100%" }}
            transition={{ type: "spring", damping: 25, stiffness: 200 }}
            className="absolute top-0 right-0 h-full w-full max-w-xl bg-white dark:bg-gray-950 shadow-2xl flex flex-col border-l border-gray-200 dark:border-gray-800"
          >
            {/* Header */}
            <div className="flex items-center justify-between px-6 py-4 border-b border-gray-200 dark:border-gray-800 bg-white/80 dark:bg-gray-950/80 backdrop-blur-md">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-xl bg-emerald-600 text-white flex items-center justify-center">
                  <Server className="w-5 h-5" />
                </div>
                <div>
                  <h2 className="text-lg font-bold text-gray-900 dark:text-white">
                    {title || (isEditing ? "Modifier l'entreprise" : "Nouvelle entreprise")}
                  </h2>
                  <p className="text-xs text-gray-500">{completion}% complété</p>
                </div>
              </div>
              <button
                onClick={onClose}
                className="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-full transition-colors"
              >
                <X className="w-5 h-5 text-gray-500" />
              </button>
            </div>

            {/* Progress bar */}
            <Progress value={completion} className="h-1 rounded-none" />

            {/* Form */}
            <form
              onSubmit={handleSubmit(handleFormSubmit, onError)}
              className="flex-1 flex flex-col overflow-hidden"
            >
              {/* Body scrollable */}
              <div className="flex-1 overflow-y-auto bg-gray-50/50 dark:bg-black/20">
                {/* Status toggles */}
                <div className="p-4 border-b border-gray-100 dark:border-gray-800">
                  <div className="flex gap-6">
                    <Controller
                      name="is_active"
                      control={control}
                      render={({ field }) => (
                        <label className="flex items-center gap-2 cursor-pointer">
                          <input
                            type="checkbox"
                            checked={field.value !== false}
                            onChange={(e) => field.onChange(e.target.checked)}
                            className="w-4 h-4 text-emerald-600 rounded border-gray-300 focus:ring-emerald-600"
                          />
                          <span className="text-sm text-gray-700 dark:text-gray-300">
                            Active
                          </span>
                        </label>
                      )}
                    />
                    <Controller
                      name="is_default"
                      control={control}
                      render={({ field }) => (
                        <label className="flex items-center gap-2 cursor-pointer">
                          <input
                            type="checkbox"
                            checked={field.value || false}
                            onChange={(e) => field.onChange(e.target.checked)}
                            className="w-4 h-4 text-blue-600 rounded border-gray-300 focus:ring-blue-600"
                          />
                          <span className="text-sm text-gray-700 dark:text-gray-300">
                            Par défaut
                          </span>
                        </label>
                      )}
                    />
                  </div>
                </div>

                {/* Section: Identification */}
                <Section title="Identification" icon={Server} defaultOpen={true}>
                  <Controller
                    name="name"
                    control={control}
                    render={({ field }) => (
                      <InputField
                        {...field}
                        label="Nom de la gateway"
                        inputType="text"
                        required
                        placeholder="Ex: Gateway Production"
                        error={errors.name?.message}
                      />
                    )}
                  />
                  <Controller
                    name="description"
                    control={control}
                    render={({ field }) => (
                      <InputField
                        {...field}
                        value={field.value || ""}
                        label="Description"
                        inputType="text"
                        // as="textarea"
                        placeholder="Description optionnelle de la gateway..."
                        error={errors.description?.message}
                        // rows={3}
                      />
                    )}
                  />
                </Section>

                {/* Section: Connexion */}
                <Section title="Connexion" icon={Link} defaultOpen={true}>
                  <Controller
                    name="gateway_url"
                    control={control}
                    render={({ field }) => (
                      <InputField
                        {...field}
                        label="URL de la gateway"
                        inputType="url"
                        required
                        placeholder="https://gateway.exemple.com"
                        error={errors.gateway_url?.message}
                        leftIcon={<Link className="w-4 h-4" />}
                      />
                    )}
                  />
                  <Controller
                    name="token_preview"
                    control={control}
                    render={({ field }) => (
                      <div className="relative">
                        <InputField
                          {...field}
                          label="Token d'authentification"
                          inputType={showToken ? "text" : "password"}
                          required
                          placeholder="Votre token secret..."
                          error={errors.token_preview?.message}
                          leftIcon={<Key className="w-4 h-4" />}
                          className="pr-10 font-mono"
                        />
                        <button
                          type="button"
                          onClick={() => setShowToken(!showToken)}
                          className="absolute right-3 top-[34px] p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
                        >
                          {showToken ? (
                            <EyeOff className="w-4 h-4" />
                          ) : (
                            <Eye className="w-4 h-4" />
                          )}
                        </button>
                      </div>
                    )}
                  />
                </Section>

                {/* Section: Configuration Sage */}
                <Section title="Configuration Sage" icon={Database} defaultOpen={false}>
                  <Controller
                    name="sage_database"
                    control={control}
                    render={({ field }) => (
                      <InputField
                        {...field}
                        value={field.value || ""}
                        label="Base de données Sage"
                        inputType="text"
                        placeholder="Ex: SAGE_PROD"
                        error={errors.sage_database?.message}
                        leftIcon={<Database className="w-4 h-4" />}
                      />
                    )}
                  />
                  <Controller
                    name="sage_company"
                    control={control}
                    render={({ field }) => (
                      <InputField
                        {...field}
                        value={field.value || ""}
                        label="Société Sage"
                        inputType="text"
                        placeholder="Ex: Ma Société SARL"
                        error={errors.sage_company?.message}
                        leftIcon={<Building2 className="w-4 h-4" />}
                      />
                    )}
                  />
                </Section>
              </div>

              {/* Footer */}
              <div className="p-4 border-t border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-950 flex justify-end gap-3">
                <button
                  type="button"
                  onClick={onClose}
                  className="px-4 py-2.5 text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-xl transition-colors"
                >
                  Annuler
                </button>
                <button
                  type="submit"
                  disabled={!canSave || isSubmitting}
                  className={cn(
                    "inline-flex items-center gap-2 px-6 py-2.5 text-white text-sm font-medium rounded-xl shadow-lg shadow-emerald-900/20 transition-colors",
                    canSave && !isSubmitting
                      ? "bg-[#007E45] hover:bg-[#006838]"
                      : "bg-gray-400 cursor-not-allowed"
                  )}
                >
                  {isSubmitting ? (
                    <Loader2 className="w-4 h-4 animate-spin" />
                  ) : (
                    <Save className="w-4 h-4" />
                  )}
                  {isEditing ? "Mettre à jour" : "Créer la gateway"}
                </button>
              </div>
            </form>
          </motion.div>
        </div>
      )}
    </AnimatePresence>,
    document.body
  );
}

export default ModalGateway;