'use client';

import { useState, useEffect } from 'react';
import { EmergencyContact } from '@/types/medical';
import { api } from '@/lib/api';
import EmergencyContactModal, { EmergencyContactFormData } from './EmergencyContactModal';
import DeleteEmergencyContactModal from './DeleteEmergencyContactModal';

interface EmergencyContactManagementProps {
  token: string;
  onClose: () => void;
}

export default function EmergencyContactManagement({
  token,
  onClose,
}: EmergencyContactManagementProps) {
  const [contacts, setContacts] = useState<EmergencyContact[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);

  // États pour les modals
  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [selectedContact, setSelectedContact] = useState<EmergencyContact | null>(null);

  // Charger les contacts
  const loadContacts = async () => {
    try {
      setLoading(true);
      setError(null);
      const data = await api.getEmergencyContacts(token);
      setContacts(data);
    } catch (err: any) {
      setError(err.message || 'Erreur lors du chargement des contacts');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadContacts();
  }, [token]);

  // Bloquer le scroll du body
  useEffect(() => {
    document.body.classList.add('modal-open');
    return () => {
      document.body.classList.remove('modal-open');
    };
  }, []);

  // Créer un contact
  const handleCreate = async (data: EmergencyContactFormData) => {
    await api.createEmergencyContact(token, data);
    setSuccessMessage('Contact créé avec succès');
    await loadContacts();
    setTimeout(() => setSuccessMessage(null), 3000);
  };

  // Modifier un contact
  const handleUpdate = async (data: EmergencyContactFormData) => {
    if (!selectedContact) return;
    await api.updateEmergencyContact(token, selectedContact.id, data);
    setSuccessMessage('Contact modifié avec succès');
    setSelectedContact(null);
    await loadContacts();
    setTimeout(() => setSuccessMessage(null), 3000);
  };

  // Supprimer un contact
  const handleDelete = async () => {
    if (!selectedContact) return;
    await api.deleteEmergencyContact(token, selectedContact.id);
    setSuccessMessage('Contact supprimé avec succès');
    await loadContacts();
    setTimeout(() => setSuccessMessage(null), 3000);
  };

  // Ouvrir le modal d'édition
  const openEditModal = (contact: EmergencyContact) => {
    setSelectedContact(contact);
    setIsEditModalOpen(true);
  };

  // Ouvrir le modal de suppression
  const openDeleteModal = (contact: EmergencyContact) => {
    setSelectedContact(contact);
    setIsDeleteModalOpen(true);
  };

  return (
    <div
      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: 9998,
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          backgroundColor: 'white',
          borderRadius: '12px',
          boxShadow: '0 20px 25px -5px rgba(0, 0, 0, 0.1)',
          maxWidth: '900px',
          width: '100%',
          margin: '0 16px',
          maxHeight: '90vh',
          display: 'flex',
          flexDirection: 'column',
        }}
      >
        {/* Header */}
        <div
          style={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            padding: '24px',
            borderBottom: '1px solid #E5E7EB',
            backgroundColor: '#F9FAFB',
            borderTopLeftRadius: '12px',
            borderTopRightRadius: '12px',
          }}
        >
          <div>
            <h2
              style={{
                fontSize: '24px',
                fontWeight: '600',
                color: '#111827',
                margin: 0,
              }}
            >
              Gestion des Contacts d'urgence
            </h2>
            {!loading && (
              <p
                style={{
                  fontSize: '14px',
                  color: '#6B7280',
                  marginTop: '4px',
                }}
              >
                {contacts.length} contact{contacts.length > 1 ? 's' : ''} enregistré
                {contacts.length > 1 ? 's' : ''}
              </p>
            )}
          </div>
          <button
            onClick={onClose}
            title="Fermer"
            style={{
              color: '#9CA3AF',
              cursor: 'pointer',
              background: 'none',
              border: 'none',
              padding: '8px',
              borderRadius: '9999px',
            }}
          >
            <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>

        {/* Messages */}
        {successMessage && (
          <div
            style={{
              margin: '16px 24px 0',
              backgroundColor: '#F0FDF4',
              border: '1px solid #86EFAC',
              color: '#15803D',
              padding: '12px 16px',
              borderRadius: '6px',
            }}
          >
            {successMessage}
          </div>
        )}

        {error && (
          <div
            style={{
              margin: '16px 24px 0',
              backgroundColor: '#FEF2F2',
              border: '1px solid #FCA5A5',
              color: '#991B1B',
              padding: '12px 16px',
              borderRadius: '6px',
            }}
          >
            {error}
          </div>
        )}

        {/* Bouton Ajouter */}
        <div
          style={{
            padding: '16px 24px',
            borderBottom: '1px solid #E5E7EB',
          }}
        >
          <button
            onClick={() => setIsCreateModalOpen(true)}
            style={{
              width: '100%',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              gap: '8px',
              padding: '12px 16px',
              backgroundColor: '#2563EB',
              color: 'white',
              border: 'none',
              borderRadius: '8px',
              fontWeight: '500',
              cursor: 'pointer',
              boxShadow: '0 1px 2px 0 rgba(0, 0, 0, 0.05)',
            }}
          >
            <svg
              style={{ width: '20px', height: '20px' }}
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M12 4v16m8-8H4"
              />
            </svg>
            <span>Ajouter un contact d'urgence</span>
          </button>
        </div>

        {/* Liste des contacts */}
        <div
          style={{
            flex: 1,
            overflowY: 'auto',
            padding: '24px',
            minHeight: 0,
          }}
        >
          {loading ? (
            <div
              style={{
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',
                padding: '48px',
              }}
            >
              <svg
                style={{
                  animation: 'spin 1s linear infinite',
                  width: '40px',
                  height: '40px',
                  color: '#2563EB',
                }}
                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>
            </div>
          ) : contacts.length === 0 ? (
            <div
              style={{
                textAlign: 'center',
                padding: '48px',
                color: '#6B7280',
              }}
            >
              <svg
                style={{
                  width: '64px',
                  height: '64px',
                  margin: '0 auto 16px',
                  color: '#D1D5DB',
                }}
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"
                />
              </svg>
              <p style={{ fontSize: '16px', fontWeight: '500', marginBottom: '8px' }}>
                Aucun contact d'urgence
              </p>
              <p style={{ fontSize: '14px' }}>
                Cliquez sur "Ajouter un contact d'urgence" pour commencer
              </p>
            </div>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
              {contacts.map((contact) => (
                <div
                  key={contact.id}
                  style={{
                    backgroundColor: 'white',
                    border: '1px solid #E5E7EB',
                    borderRadius: '8px',
                    padding: '16px',
                    display: 'flex',
                    alignItems: 'center',
                    gap: '16px',
                  }}
                >
                  {/* Avatar */}
                  <div
                    style={{
                      width: '48px',
                      height: '48px',
                      borderRadius: '50%',
                      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      color: 'white',
                      fontSize: '18px',
                      fontWeight: '600',
                      flexShrink: 0,
                    }}
                  >
                    {contact.firstname.charAt(0)}
                    {contact.name.charAt(0)}
                  </div>

                  {/* Infos */}
                  <div style={{ flex: 1 }}>
                    <h3
                      style={{
                        fontSize: '16px',
                        fontWeight: '600',
                        color: '#111827',
                        margin: '0 0 8px 0',
                      }}
                    >
                      {contact.firstname} {contact.name}
                    </h3>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
                      <div style={{ fontSize: '14px', color: '#6B7280' }}>
                        <strong>Lien:</strong> {contact.filiation}
                      </div>
                      <div style={{ fontSize: '14px', color: '#6B7280' }}>
                        <strong>Téléphone:</strong> {contact.phone}
                      </div>
                    </div>
                  </div>

                  {/* Actions */}
                  <div style={{ display: 'flex', gap: '8px', flexShrink: 0 }}>
                    <button
                      onClick={() => openEditModal(contact)}
                      title="Modifier"
                      style={{
                        padding: '8px',
                        backgroundColor: '#EFF6FF',
                        color: '#2563EB',
                        border: 'none',
                        borderRadius: '6px',
                        cursor: 'pointer',
                      }}
                    >
                      <svg
                        style={{ width: '20px', height: '20px' }}
                        fill="none"
                        stroke="currentColor"
                        viewBox="0 0 24 24"
                      >
                        <path
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          strokeWidth={2}
                          d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"
                        />
                      </svg>
                    </button>
                    <button
                      onClick={() => openDeleteModal(contact)}
                      title="Supprimer"
                      style={{
                        padding: '8px',
                        backgroundColor: '#FEF2F2',
                        color: '#DC2626',
                        border: 'none',
                        borderRadius: '6px',
                        cursor: 'pointer',
                      }}
                    >
                      <svg
                        style={{ width: '20px', height: '20px' }}
                        fill="none"
                        stroke="currentColor"
                        viewBox="0 0 24 24"
                      >
                        <path
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          strokeWidth={2}
                          d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
                        />
                      </svg>
                    </button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* Modals */}
      {isCreateModalOpen && (
        <EmergencyContactModal
          title="Ajouter un contact d'urgence"
          onClose={() => setIsCreateModalOpen(false)}
          onSubmit={handleCreate}
        />
      )}

      {isEditModalOpen && selectedContact && (
        <EmergencyContactModal
          title="Modifier le contact"
          contact={selectedContact}
          onClose={() => {
            setIsEditModalOpen(false);
            setSelectedContact(null);
          }}
          onSubmit={handleUpdate}
        />
      )}

      {isDeleteModalOpen && selectedContact && (
        <DeleteEmergencyContactModal
          contact={selectedContact}
          onClose={() => {
            setIsDeleteModalOpen(false);
            setSelectedContact(null);
          }}
          onConfirm={handleDelete}
        />
      )}
    </div>
  );
}
