import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Badge } from '@/components/ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { apiRequest } from '@/lib/queryClient';
import { useToast } from '@/hooks/use-toast';
import {
  Heart,
  AlertTriangle,
  Plus,
  Edit,
  Save,
  X,
  User,
  Calendar,
  Pill,
  Activity,
  Shield,
  Clock
} from 'lucide-react';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';

interface MedicalCondition {
  id: string;
  name: string;
  severity: 'low' | 'medium' | 'high';
  diagnosedDate: string;
  notes?: string;
}

interface MedicalAllergy {
  id: string;
  allergen: string;
  reaction: string;
  severity: 'mild' | 'moderate' | 'severe';
}

interface CurrentMedication {
  id: string;
  name: string;
  dosage: string;
  frequency: string;
  prescribedBy: string;
  startDate: string;
}

interface MedicalProfile {
  id: string;
  bloodType: string;
  height: number;
  weight: number;
  emergencyContact: {
    name: string;
    phone: string;
    relationship: string;
  };
  conditions: MedicalCondition[];
  allergies: MedicalAllergy[];
  currentMedications: CurrentMedication[];
  lastUpdated: string;
}

interface MedicalProfileProps {
  userId: string;
}

export function MedicalProfile({ userId }: MedicalProfileProps) {
  const [isEditing, setIsEditing] = useState(false);
  const [showAddCondition, setShowAddCondition] = useState(false);
  const [showAddAllergy, setShowAddAllergy] = useState(false);
  const [editingProfile, setEditingProfile] = useState<Partial<MedicalProfile>>({});
  
  const { toast } = useToast();
  const queryClient = useQueryClient();

  // Fetch medical profile
  const { data: profile, isLoading } = useQuery<MedicalProfile>({
    queryKey: ['/api/medical-profile', userId],
    initialData: {
      id: userId,
      bloodType: 'O+',
      height: 170,
      weight: 70,
      emergencyContact: {
        name: 'Contact d\'urgence',
        phone: '+225 00 00 00 00',
        relationship: 'Famille'
      },
      conditions: [
        {
          id: '1',
          name: 'Hypertension',
          severity: 'medium',
          diagnosedDate: '2023-01-15',
          notes: 'Contrôlée par médicaments'
        },
        {
          id: '2',
          name: 'Diabète Type 2',
          severity: 'high',
          diagnosedDate: '2022-08-20',
          notes: 'Suivi régulier nécessaire'
        }
      ],
      allergies: [
        {
          id: '1',
          allergen: 'Pénicilline',
          reaction: 'Éruption cutanée',
          severity: 'moderate'
        },
        {
          id: '2',
          allergen: 'Arachides',
          reaction: 'Gonflement, difficultés respiratoires',
          severity: 'severe'
        }
      ],
      currentMedications: [
        {
          id: '1',
          name: 'Lisinopril',
          dosage: '10mg',
          frequency: '1 fois par jour',
          prescribedBy: 'Dr. Kouame',
          startDate: '2023-01-15'
        },
        {
          id: '2',
          name: 'Metformine',
          dosage: '500mg',
          frequency: '2 fois par jour',
          prescribedBy: 'Dr. Assi',
          startDate: '2022-08-20'
        }
      ],
      lastUpdated: new Date().toISOString()
    }
  });

  // Update medical profile mutation
  const updateProfileMutation = useMutation({
    mutationFn: async (data: Partial<MedicalProfile>) => {
      return await apiRequest('/api/medical-profile', {
        method: 'PUT',
        body: JSON.stringify({ ...profile, ...data })
      });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['/api/medical-profile', userId] });
      toast({
        title: "Profil médical mis à jour",
        description: "Vos informations médicales ont été sauvegardées avec succès.",
      });
      setIsEditing(false);
    },
    onError: () => {
      toast({
        title: "Erreur",
        description: "Impossible de mettre à jour votre profil médical.",
        variant: "destructive",
      });
    },
  });

  const getSeverityBadge = (severity: string) => {
    const variants = {
      low: 'bg-green-100 text-green-800',
      mild: 'bg-green-100 text-green-800',
      medium: 'bg-yellow-100 text-yellow-800',
      moderate: 'bg-yellow-100 text-yellow-800',
      high: 'bg-red-100 text-red-800',
      severe: 'bg-red-100 text-red-800'
    };
    
    return (
      <Badge className={variants[severity as keyof typeof variants] || 'bg-gray-100 text-gray-800'}>
        {severity}
      </Badge>
    );
  };

  const handleSave = () => {
    if (editingProfile) {
      updateProfileMutation.mutate(editingProfile);
    }
  };

  if (isLoading || !profile) {
    return (
      <Card>
        <CardContent className="p-6">
          <div className="animate-pulse space-y-4">
            <div className="h-4 bg-gray-200 rounded w-1/3"></div>
            <div className="h-4 bg-gray-200 rounded w-1/2"></div>
            <div className="h-4 bg-gray-200 rounded w-2/3"></div>
          </div>
        </CardContent>
      </Card>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle className="flex items-center gap-2">
              <Heart className="h-5 w-5 text-red-500" />
              Profil Médical
            </CardTitle>
            <div className="flex items-center gap-2">
              <Badge variant="outline" className="text-xs">
                <Clock className="h-3 w-3 mr-1" />
                Mis à jour: {new Date(profile.lastUpdated).toLocaleDateString('fr-FR')}
              </Badge>
              {!isEditing ? (
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => {
                    setIsEditing(true);
                    setEditingProfile(profile);
                  }}
                  data-testid="button-edit-profile"
                >
                  <Edit className="h-4 w-4 mr-1" />
                  Modifier
                </Button>
              ) : (
                <div className="flex gap-2">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => setIsEditing(false)}
                    data-testid="button-cancel-edit"
                  >
                    <X className="h-4 w-4 mr-1" />
                    Annuler
                  </Button>
                  <Button
                    size="sm"
                    onClick={handleSave}
                    disabled={updateProfileMutation.isPending}
                    data-testid="button-save-profile"
                  >
                    <Save className="h-4 w-4 mr-1" />
                    Sauvegarder
                  </Button>
                </div>
              )}
            </div>
          </div>
        </CardHeader>
        <CardContent>
          <div className="grid md:grid-cols-2 lg:grid-cols-4 gap-4">
            <div className="flex items-center gap-3">
              <Activity className="h-8 w-8 text-blue-500" />
              <div>
                <p className="text-sm text-muted-foreground">Groupe Sanguin</p>
                {isEditing ? (
                  <Select
                    value={editingProfile.bloodType || profile.bloodType}
                    onValueChange={(value) =>
                      setEditingProfile(prev => ({ ...prev, bloodType: value }))
                    }
                  >
                    <SelectTrigger className="w-full">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="A+">A+</SelectItem>
                      <SelectItem value="A-">A-</SelectItem>
                      <SelectItem value="B+">B+</SelectItem>
                      <SelectItem value="B-">B-</SelectItem>
                      <SelectItem value="AB+">AB+</SelectItem>
                      <SelectItem value="AB-">AB-</SelectItem>
                      <SelectItem value="O+">O+</SelectItem>
                      <SelectItem value="O-">O-</SelectItem>
                    </SelectContent>
                  </Select>
                ) : (
                  <p className="font-medium text-red-600">{profile.bloodType}</p>
                )}
              </div>
            </div>
            
            <div className="flex items-center gap-3">
              <User className="h-8 w-8 text-green-500" />
              <div>
                <p className="text-sm text-muted-foreground">Taille</p>
                {isEditing ? (
                  <Input
                    type="number"
                    value={editingProfile.height || profile.height}
                    onChange={(e) =>
                      setEditingProfile(prev => ({ ...prev, height: parseInt(e.target.value) }))
                    }
                    className="w-20"
                  />
                ) : (
                  <p className="font-medium">{profile.height} cm</p>
                )}
              </div>
            </div>
            
            <div className="flex items-center gap-3">
              <Activity className="h-8 w-8 text-purple-500" />
              <div>
                <p className="text-sm text-muted-foreground">Poids</p>
                {isEditing ? (
                  <Input
                    type="number"
                    value={editingProfile.weight || profile.weight}
                    onChange={(e) =>
                      setEditingProfile(prev => ({ ...prev, weight: parseInt(e.target.value) }))
                    }
                    className="w-20"
                  />
                ) : (
                  <p className="font-medium">{profile.weight} kg</p>
                )}
              </div>
            </div>
            
            <div className="flex items-center gap-3">
              <Shield className="h-8 w-8 text-orange-500" />
              <div>
                <p className="text-sm text-muted-foreground">Contact d'urgence</p>
                <p className="font-medium text-sm">{profile.emergencyContact.name}</p>
                <p className="text-xs text-muted-foreground">{profile.emergencyContact.phone}</p>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Medical Conditions */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle className="flex items-center gap-2">
              <AlertTriangle className="h-5 w-5 text-orange-500" />
              Conditions Médicales
            </CardTitle>
            <Dialog open={showAddCondition} onOpenChange={setShowAddCondition}>
              <DialogTrigger asChild>
                <Button variant="outline" size="sm">
                  <Plus className="h-4 w-4 mr-1" />
                  Ajouter
                </Button>
              </DialogTrigger>
              <DialogContent>
                <DialogHeader>
                  <DialogTitle>Ajouter une condition médicale</DialogTitle>
                  <DialogDescription>
                    Ajoutez une nouvelle condition médicale à votre profil.
                  </DialogDescription>
                </DialogHeader>
                {/* Add condition form would go here */}
              </DialogContent>
            </Dialog>
          </div>
        </CardHeader>
        <CardContent>
          <div className="space-y-3">
            {profile.conditions.map((condition) => (
              <div
                key={condition.id}
                className="flex items-center justify-between p-3 border rounded-lg"
                data-testid={`condition-${condition.id}`}
              >
                <div className="flex-1">
                  <div className="flex items-center gap-2 mb-1">
                    <h4 className="font-medium">{condition.name}</h4>
                    {getSeverityBadge(condition.severity)}
                  </div>
                  <p className="text-sm text-muted-foreground">
                    Diagnostiqué le {new Date(condition.diagnosedDate).toLocaleDateString('fr-FR')}
                  </p>
                  {condition.notes && (
                    <p className="text-sm text-muted-foreground mt-1">{condition.notes}</p>
                  )}
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      {/* Allergies */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle className="flex items-center gap-2">
              <AlertTriangle className="h-5 w-5 text-red-500" />
              Allergies
            </CardTitle>
            <Dialog open={showAddAllergy} onOpenChange={setShowAddAllergy}>
              <DialogTrigger asChild>
                <Button variant="outline" size="sm">
                  <Plus className="h-4 w-4 mr-1" />
                  Ajouter
                </Button>
              </DialogTrigger>
              <DialogContent>
                <DialogHeader>
                  <DialogTitle>Ajouter une allergie</DialogTitle>
                  <DialogDescription>
                    Ajoutez une nouvelle allergie à votre profil médical.
                  </DialogDescription>
                </DialogHeader>
                {/* Add allergy form would go here */}
              </DialogContent>
            </Dialog>
          </div>
        </CardHeader>
        <CardContent>
          <div className="space-y-3">
            {profile.allergies.map((allergy) => (
              <div
                key={allergy.id}
                className="flex items-center justify-between p-3 border rounded-lg bg-red-50"
                data-testid={`allergy-${allergy.id}`}
              >
                <div className="flex-1">
                  <div className="flex items-center gap-2 mb-1">
                    <h4 className="font-medium text-red-800">{allergy.allergen}</h4>
                    {getSeverityBadge(allergy.severity)}
                  </div>
                  <p className="text-sm text-red-600">{allergy.reaction}</p>
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      {/* Current Medications */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Pill className="h-5 w-5 text-blue-500" />
            Médicaments Actuels
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-3">
            {profile.currentMedications.map((medication) => (
              <div
                key={medication.id}
                className="flex items-center justify-between p-3 border rounded-lg"
                data-testid={`medication-${medication.id}`}
              >
                <div className="flex-1">
                  <div className="flex items-center gap-2 mb-1">
                    <h4 className="font-medium">{medication.name}</h4>
                    <Badge variant="secondary">{medication.dosage}</Badge>
                  </div>
                  <p className="text-sm text-muted-foreground">{medication.frequency}</p>
                  <p className="text-xs text-muted-foreground">
                    Prescrit par {medication.prescribedBy} • 
                    Depuis le {new Date(medication.startDate).toLocaleDateString('fr-FR')}
                  </p>
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}