'use client';

import { useState, useEffect } from 'react';
import { Client } from '@/types/medical';

interface ClientModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSubmit: (data: ClientFormData) => Promise<void>;
  client?: Client;
  title: string;
}

export interface ClientFormData {
  name: string;
  firstName: string;
  dateOfBirth: string;
  adress: string;
  geographicCoordinates?: string;
}

export default function ClientModal({
  isOpen,
  onClose,
  onSubmit,
  client,
  title,
}: ClientModalProps) {
  const [formData, setFormData] = useState<ClientFormData>({
    name: '',
    firstName: '',
    dateOfBirth: '',
    adress: '',
    geographicCoordinates: '',
  });
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [isGeocoding, setIsGeocoding] = useState(false);
  const [googleMapsUrl, setGoogleMapsUrl] = useState<string | null>(null);

  useEffect(() => {
    if (client) {
      // Convertir la date au format YYYY-MM-DD pour l'input type="date"
      let formattedDate = '';
      if (client.dateOfBirth) {
        try {
          const date = new Date(client.dateOfBirth);
          formattedDate = date.toISOString().split('T')[0];
        } catch (e) {
          console.error('Erreur de parsing de date:', e);
        }
      }
      
      setFormData({
        name: client.name || '',
        firstName: client.firstName || '',
        dateOfBirth: formattedDate,
        adress: client.adress || '',
        geographicCoordinates: client.geographicCoordinates || '',
      });
    } else {
      setFormData({
        name: '',
        firstName: '',
        dateOfBirth: '',
        adress: '',
        geographicCoordinates: '',
      });
    }
    setError(null);
    setGoogleMapsUrl(null);
  }, [client, isOpen]);

  // Bloquer le scroll du body quand la modale est ouverte
  useEffect(() => {
    if (isOpen) {
      document.body.classList.add('modal-open');
    } else {
      document.body.classList.remove('modal-open');
    }
    return () => {
      document.body.classList.remove('modal-open');
    };
  }, [isOpen]);

  // Fonction pour géocoder l'adresse
  const geocodeAddress = async () => {
    if (!formData.adress.trim()) {
      setError('Veuillez entrer une adresse');
      return;
    }

    setIsGeocoding(true);
    setError(null);

    try {
      // Utiliser l'API Nominatim d'OpenStreetMap (gratuite) avec plus de détails
      const response = await fetch(
        `https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(formData.adress)}&limit=1&addressdetails=1&extratags=1`,
        {
          headers: {
            'User-Agent': 'MarylineApps',
          },
        }
      );

      if (!response.ok) {
        throw new Error('Erreur lors de la recherche de l\'adresse');
      }

      const data = await response.json();

      if (data.length === 0) {
        setError('Adresse non trouvée. Vérifiez l\'orthographe ou soyez plus précis (rue, ville, code postal).');
        return;
      }

      console.log('📍 Résultat géolocalisation:', data[0]);
      console.log('📍 Type de lieu:', data[0].type, '| Importance:', data[0].importance);

      // Convertir en format DMS (degrés, minutes, secondes)
      const lat = parseFloat(data[0].lat);
      const lon = parseFloat(data[0].lon);
      
      const convertToDMS = (decimal: number, isLatitude: boolean) => {
        const absolute = Math.abs(decimal);
        const degrees = Math.floor(absolute);
        const minutesNotTruncated = (absolute - degrees) * 60;
        const minutes = Math.floor(minutesNotTruncated);
        const seconds = ((minutesNotTruncated - minutes) * 60).toFixed(1);
        
        const direction = decimal >= 0 
          ? (isLatitude ? 'N' : 'E') 
          : (isLatitude ? 'S' : 'W');
        
        return `${degrees}°${minutes}'${seconds}"${direction}`;
      };

      const latDMS = convertToDMS(lat, true);
      const lonDMS = convertToDMS(lon, false);
      const coordinates = `${latDMS} ${lonDMS}`;

      const mapsUrl = `https://www.google.com/maps/search/?api=1&query=${lat},${lon}`;
      
      setFormData({ ...formData, geographicCoordinates: coordinates });
      setGoogleMapsUrl(mapsUrl);
      console.log('✅ Coordonnées trouvées:', coordinates);
      console.log('🗺️ Vérifier sur Google Maps:', mapsUrl);
    } catch (err: any) {
      console.error('❌ Erreur géocodage:', err);
      setError(err.message || 'Erreur lors de la recherche des coordonnées');
    } finally {
      setIsGeocoding(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    setIsSubmitting(true);

    try {
      await onSubmit(formData);
      onClose();
    } catch (err: any) {
      setError(err.message || 'Une erreur est survenue');
    } finally {
      setIsSubmitting(false);
    }
  };

  if (!isOpen) return null;

  return (
    <div 
      className="modal-overlay"
      onClick={onClose}
      style={{
        position: 'fixed',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        zIndex: 9999,
      }}
    >
      <div 
        className="modal-content"
        onClick={(e) => e.stopPropagation()}
        style={{
          backgroundColor: 'white',
          borderRadius: '12px',
          boxShadow: '0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)',
          maxWidth: '500px',
          width: '100%',
          margin: '0 16px',
          maxHeight: '90vh',
          overflow: 'auto',
        }}
      >
        <div style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          padding: '24px',
          borderBottom: '1px solid #e5e7eb',
        }}>
          <h2 style={{
            fontSize: '20px',
            fontWeight: '600',
            color: '#111827',
            margin: 0,
          }}>{title}</h2>
          <button
            onClick={onClose}
            disabled={isSubmitting}
            style={{
              color: '#9ca3af',
              cursor: isSubmitting ? 'not-allowed' : 'pointer',
              background: 'none',
              border: 'none',
              padding: '4px',
            }}
          >
            <svg
              style={{ width: '24px', height: '24px' }}
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M6 18L18 6M6 6l12 12"
              />
            </svg>
          </button>
        </div>

        <form onSubmit={handleSubmit} style={{ padding: '24px' }}>
          {error && (
            <div style={{
              backgroundColor: '#FEF2F2',
              borderLeft: '4px solid #EF4444',
              color: '#991B1B',
              padding: '12px 16px',
              borderRadius: '4px',
              marginBottom: '20px',
            }}>
              {error}
            </div>
          )}

          <div style={{ marginBottom: '20px' }}>
            <label htmlFor="name" style={{
              display: 'block',
              fontSize: '14px',
              fontWeight: '600',
              color: '#374151',
              marginBottom: '8px',
            }}>
              Nom <span style={{ color: '#EF4444' }}>*</span>
            </label>
            <input
              type="text"
              id="name"
              required
              value={formData.name}
              onChange={(e) => setFormData({ ...formData, name: e.target.value })}
              disabled={isSubmitting}
              placeholder="DE MEYER"
              style={{
                width: '100%',
                padding: '10px 12px',
                border: '2px solid #D1D5DB',
                borderRadius: '8px',
                fontSize: '14px',
                outline: 'none',
                boxSizing: 'border-box',
              }}
            />
          </div>

          <div style={{ marginBottom: '20px' }}>
            <label htmlFor="firstName" style={{
              display: 'block',
              fontSize: '14px',
              fontWeight: '600',
              color: '#374151',
              marginBottom: '8px',
            }}>
              Prénom <span style={{ color: '#EF4444' }}>*</span>
            </label>
            <input
              type="text"
              id="firstName"
              required
              value={formData.firstName}
              onChange={(e) => setFormData({ ...formData, firstName: e.target.value })}
              disabled={isSubmitting}
              placeholder="Maryline"
              style={{
                width: '100%',
                padding: '10px 12px',
                border: '2px solid #D1D5DB',
                borderRadius: '8px',
                fontSize: '14px',
                outline: 'none',
                boxSizing: 'border-box',
              }}
            />
          </div>

          <div style={{ marginBottom: '20px' }}>
            <label htmlFor="dateOfBirth" style={{
              display: 'block',
              fontSize: '14px',
              fontWeight: '600',
              color: '#374151',
              marginBottom: '8px',
            }}>
              Date de naissance <span style={{ color: '#EF4444' }}>*</span>
            </label>
            <input
              type="date"
              id="dateOfBirth"
              required
              value={formData.dateOfBirth}
              onChange={(e) => setFormData({ ...formData, dateOfBirth: e.target.value })}
              disabled={isSubmitting}
              style={{
                width: '100%',
                padding: '10px 12px',
                border: '2px solid #D1D5DB',
                borderRadius: '8px',
                fontSize: '14px',
                outline: 'none',
                boxSizing: 'border-box',
              }}
            />
          </div>

          <div style={{ marginBottom: '20px' }}>
            <label htmlFor="adress" style={{
              display: 'block',
              fontSize: '14px',
              fontWeight: '600',
              color: '#374151',
              marginBottom: '8px',
            }}>
              Adresse <span style={{ color: '#EF4444' }}>*</span>
            </label>
            <textarea
              id="adress"
              required
              rows={3}
              value={formData.adress}
              onChange={(e) => setFormData({ ...formData, adress: e.target.value })}
              disabled={isSubmitting}
              placeholder="24 résidence Jeanne Lecu, Chemin des charbonniers 59215 ABSCON"
              style={{
                width: '100%',
                padding: '10px 12px',
                border: '2px solid #D1D5DB',
                borderRadius: '8px',
                fontSize: '14px',
                outline: 'none',
                resize: 'vertical',
                fontFamily: 'inherit',
                boxSizing: 'border-box',
              }}
            />
          </div>

          <div style={{ marginBottom: '20px' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>
              <label htmlFor="geographicCoordinates" style={{
                fontSize: '14px',
                fontWeight: '600',
                color: '#374151',
              }}>
                Coordonnées GPS <span style={{ fontSize: '12px', fontWeight: 'normal', color: '#6B7280' }}>(optionnel)</span>
              </label>
              <button
                type="button"
                onClick={geocodeAddress}
                disabled={isGeocoding || isSubmitting || !formData.adress.trim()}
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: '6px',
                  padding: '6px 12px',
                  backgroundColor: isGeocoding || !formData.adress.trim() ? '#D1D5DB' : '#10B981',
                  color: 'white',
                  border: 'none',
                  borderRadius: '6px',
                  fontSize: '12px',
                  fontWeight: '600',
                  cursor: isGeocoding || !formData.adress.trim() ? 'not-allowed' : 'pointer',
                  transition: 'all 0.2s',
                }}
              >
                {isGeocoding ? (
                  <>
                    <svg
                      style={{
                        width: '14px',
                        height: '14px',
                        animation: 'spin 1s linear infinite',
                      }}
                      fill="none"
                      viewBox="0 0 24 24"
                    >
                      <circle
                        style={{ opacity: 0.25 }}
                        cx="12"
                        cy="12"
                        r="10"
                        stroke="currentColor"
                        strokeWidth="4"
                      />
                      <path
                        style={{ opacity: 0.75 }}
                        fill="currentColor"
                        d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                      />
                    </svg>
                    <span>Recherche...</span>
                  </>
                ) : (
                  <>
                    <span>📍</span>
                    <span>Obtenir GPS</span>
                  </>
                )}
              </button>
            </div>
            <div style={{
              backgroundColor: '#2d3748',
              borderRadius: '8px',
              padding: '12px',
              border: '2px solid #4a5568',
            }}>
              <input
                type="text"
                id="geographicCoordinates"
                placeholder="50°20'07.1&quot;N 3°17'19.9&quot;E"
                value={formData.geographicCoordinates}
                onChange={(e) => setFormData({ ...formData, geographicCoordinates: e.target.value })}
                disabled={isSubmitting || isGeocoding}
                style={{
                  width: '100%',
                  padding: '8px',
                  border: 'none',
                  borderRadius: '4px',
                  fontSize: '16px',
                  outline: 'none',
                  fontFamily: 'monospace',
                  fontWeight: '600',
                  boxSizing: 'border-box',
                  backgroundColor: '#2d3748',
                  color: '#48bb78',
                  textAlign: 'center',
                }}
              />
            </div>
            
            {/* Message d'info + bouton Google Maps */}
            <div style={{ marginTop: '8px', display: 'flex', flexDirection: 'column', gap: '8px' }}>
              <div style={{ 
                padding: '8px 12px', 
                backgroundColor: '#FEF3C7', 
                borderRadius: '6px',
                border: '1px solid #FCD34D'
              }}>
                <p style={{ margin: 0, fontSize: '12px', color: '#92400E', lineHeight: '1.5' }}>
                  💡 <strong>Astuce :</strong> Le géocodage automatique donne une position approximative. 
                  Vérifiez et ajustez manuellement si nécessaire pour plus de précision.
                </p>
              </div>

              {/* Bouton Google Maps */}
              {googleMapsUrl && (
                <a
                  href={googleMapsUrl}
                  target="_blank"
                  rel="noopener noreferrer"
                  style={{
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    gap: '8px',
                    padding: '10px 16px',
                    backgroundColor: '#3B82F6',
                    color: 'white',
                    textDecoration: 'none',
                    borderRadius: '8px',
                    fontSize: '14px',
                    fontWeight: '600',
                    transition: 'all 0.2s',
                    border: 'none',
                    cursor: 'pointer',
                  }}
                  onMouseEnter={(e) => {
                    e.currentTarget.style.backgroundColor = '#2563EB';
                    e.currentTarget.style.transform = 'translateY(-2px)';
                    e.currentTarget.style.boxShadow = '0 4px 12px rgba(37, 99, 235, 0.3)';
                  }}
                  onMouseLeave={(e) => {
                    e.currentTarget.style.backgroundColor = '#3B82F6';
                    e.currentTarget.style.transform = 'translateY(0)';
                    e.currentTarget.style.boxShadow = 'none';
                  }}
                >
                  <svg 
                    style={{ width: '18px', height: '18px' }} 
                    fill="currentColor" 
                    viewBox="0 0 24 24"
                  >
                    <path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/>
                  </svg>
                  <span>🗺️ Vérifier la position sur Google Maps</span>
                  <svg 
                    style={{ width: '16px', height: '16px' }} 
                    fill="none" 
                    stroke="currentColor" 
                    viewBox="0 0 24 24"
                  >
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
                  </svg>
                </a>
              )}
            </div>
          </div>

          <div style={{
            display: 'flex',
            justifyContent: 'flex-end',
            gap: '12px',
            paddingTop: '20px',
            borderTop: '1px solid #E5E7EB',
          }}>
            <button
              type="button"
              onClick={onClose}
              disabled={isSubmitting}
              style={{
                padding: '10px 20px',
                border: '2px solid #D1D5DB',
                borderRadius: '8px',
                color: '#374151',
                fontWeight: '500',
                cursor: isSubmitting ? 'not-allowed' : 'pointer',
                backgroundColor: 'white',
                opacity: isSubmitting ? 0.5 : 1,
              }}
            >
              Annuler
            </button>
            <button
              type="submit"
              disabled={isSubmitting}
              style={{
                padding: '10px 20px',
                border: 'none',
                borderRadius: '8px',
                color: 'white',
                fontWeight: '500',
                cursor: isSubmitting ? 'not-allowed' : 'pointer',
                backgroundColor: '#2563EB',
                opacity: isSubmitting ? 0.5 : 1,
              }}
            >
              {isSubmitting ? 'Enregistrement...' : 'Enregistrer'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
