'use client'

import { useState, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { ScrollArea } from '@/components/ui/scroll-area'
import { Separator } from '@/components/ui/separator'
import {
  Phone,
  Mail,
  MapPin,
  Calendar,
  FileText,
  Plus,
  Eye,
  Pencil,
  Trash2,
  Activity,
} from 'lucide-react'
import { VisionForm } from './vision-form'
import { OrdonnanceList } from './ordonnance-list'

interface Client {
  id: string
  nom: string
  prenom: string
  email: string | null
  telephone: string
  adresse: string | null
  ville: string | null
  codePostal: string | null
  dateNaissance: string | null
  notes: string | null
  createdAt: string
  updatedAt: string
}

interface Patient {
  id: string
  clientId: string
  dateCreation: string
  odSphere: number | null
  odCylindre: number | null
  odAxe: number | null
  ogSphere: number | null
  ogCylindre: number | null
  ogAxe: number | null
  addition: number | null
  pd: number | null
  hauteur: number | null
  notes: string | null
  createdAt: string
  updatedAt: string
  ordonnances?: Ordonnance[]
}

interface Ordonnance {
  id: string
  patientId: string
  numero: string
  dateEmission: string
  medecin: string | null
  notes: string | null
  createdAt: string
  updatedAt: string
}

interface ClientDetailProps {
  client: Client
  onClose: () => void
  onUpdate: () => void
}

export function ClientDetail({ client, onClose, onUpdate }: ClientDetailProps) {
  const [patients, setPatients] = useState<Patient[]>([])
  const [selectedPatient, setSelectedPatient] = useState<Patient | null>(null)
  const [isVisionFormOpen, setIsVisionFormOpen] = useState(false)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    console.log('ClientDetail mounted/updated with client:', client.id, client.nom, client.prenom)
    // Reset selected patient when client changes
    setSelectedPatient(null)
    fetchPatients()
  }, [client.id])

  const fetchPatients = async () => {
    try {
      setLoading(true)
      console.log('Fetching patients for client:', client.id, client.nom, client.prenom)
      const response = await fetch(`/api/clients/${client.id}/patients`)
      if (response.ok) {
        const data = await response.json()
        console.log('Patients received for', client.nom, client.prenom, ':', data)
        setPatients(data)
      }
    } catch (error) {
      console.error('Error fetching patients:', error)
    } finally {
      setLoading(false)
    }
  }

  const handlePatientSaved = async () => {
    setIsVisionFormOpen(false)
    setSelectedPatient(null)
    await fetchPatients()
    onUpdate()
  }

  const formatDate = (dateString: string | null) => {
    if (!dateString) return '-'
    return new Date(dateString).toLocaleDateString('fr-FR')
  }

  const getAge = (dateNaissance: string | null) => {
    if (!dateNaissance) return null
    const today = new Date()
    const birth = new Date(dateNaissance)
    let age = today.getFullYear() - birth.getFullYear()
    const monthDiff = today.getMonth() - birth.getMonth()
    if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
      age--
    }
    return age
  }

  const formatPrescription = (sphere: number | null, cylindre: number | null, axe: number | null) => {
    if (sphere === null) return '-'
    const sph = sphere.toFixed(2)
    const cyl = cylindre !== null ? ` ${cylindre >= 0 ? '+' : ''}${cylindre.toFixed(2)}` : ''
    const ax = axe !== null ? ` ax${axe}` : ''
    return `${sph}${cyl}${ax}`
  }

  const handleDeletePatient = async (patientId: string) => {
    if (!confirm('Êtes-vous sûr de vouloir supprimer cette fiche de vision ?')) {
      return
    }

    try {
      const response = await fetch(`/api/patients/${patientId}`, {
        method: 'DELETE',
      })

      if (response.ok) {
        await fetchPatients()
        onUpdate()
      } else {
        alert('Erreur lors de la suppression de la fiche de vision')
      }
    } catch (error) {
      console.error('Error deleting patient:', error)
      alert('Erreur lors de la suppression de la fiche de vision')
    }
  }

  return (
    <div className="space-y-6">
      {/* Client Information Card */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Activity className="h-5 w-5" />
            Informations du Client
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <p className="text-sm font-medium text-gray-500">Nom complet</p>
              <p className="text-lg font-semibold">
                {client.prenom} {client.nom}
                {getAge(client.dateNaissance) !== null && (
                  <Badge variant="secondary" className="ml-2">
                    {getAge(client.dateNaissance)} ans
                  </Badge>
                )}
              </p>
            </div>
            <div>
              <p className="text-sm font-medium text-gray-500">Date de naissance</p>
              <p className="flex items-center gap-2">
                <Calendar className="h-4 w-4 text-gray-400" />
                {formatDate(client.dateNaissance)}
              </p>
            </div>
          </div>

          <Separator />

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <p className="text-sm font-medium text-gray-500">Téléphone</p>
              <p className="flex items-center gap-2">
                <Phone className="h-4 w-4 text-gray-400" />
                {client.telephone}
              </p>
            </div>
            {client.email && (
              <div>
                <p className="text-sm font-medium text-gray-500">Email</p>
                <p className="flex items-center gap-2">
                  <Mail className="h-4 w-4 text-gray-400" />
                  {client.email}
                </p>
              </div>
            )}
          </div>

          {(client.adresse || client.ville || client.codePostal) && (
            <>
              <Separator />
              <div>
                <p className="text-sm font-medium text-gray-500 mb-2">Adresse</p>
                <div className="flex items-start gap-2">
                  <MapPin className="h-4 w-4 text-gray-400 mt-0.5" />
                  <div>
                    {client.adresse && <div className="text-sm">{client.adresse}</div>}
                    <div className="text-sm">
                      {client.codePostal && `${client.codePostal} `}
                      {client.ville}
                    </div>
                  </div>
                </div>
              </div>
            </>
          )}

          {client.notes && (
            <>
              <Separator />
              <div>
                <p className="text-sm font-medium text-gray-500 mb-2">Notes</p>
                <p className="text-sm bg-gray-50 p-3 rounded-lg">{client.notes}</p>
              </div>
            </>
          )}

          <Separator />

          <div className="flex justify-between items-center text-sm text-gray-500">
            <span>Créé le {formatDate(client.createdAt)}</span>
            <span>Modifié le {formatDate(client.updatedAt)}</span>
          </div>
        </CardContent>
      </Card>

      {/* Vision Measurements */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle className="flex items-center gap-2">
              <Eye className="h-5 w-5" />
              Fiches de Vision
              <Badge variant="secondary">{patients.length}</Badge>
            </CardTitle>
            <Button
              size="sm"
              onClick={() => {
                setSelectedPatient(null)
                setIsVisionFormOpen(true)
              }}
            >
              <Plus className="h-4 w-4 mr-2" />
              Nouvelle Fiche
            </Button>
          </div>
        </CardHeader>
        <CardContent>
          {loading ? (
            <p className="text-center text-gray-500 py-8">Chargement...</p>
          ) : patients.length === 0 ? (
            <div className="text-center py-8">
              <FileText className="h-12 w-12 text-gray-400 mx-auto mb-2" />
              <p className="text-gray-500">Aucune fiche de vision enregistrée</p>
            </div>
          ) : (
            <ScrollArea className="h-[400px]">
              <div className="space-y-3">
                {patients.map((patient) => (
                  <Card key={patient.id} className="p-4">
                    <div className="space-y-3">
                      <div className="flex items-start justify-between">
                        <div>
                          <p className="text-sm font-medium text-gray-500">
                            Créée le {formatDate(patient.dateCreation)}
                          </p>
                          {patient.notes && (
                            <p className="text-sm text-gray-600 mt-1">{patient.notes}</p>
                          )}
                        </div>
                        <div className="flex gap-2">
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => {
                              setSelectedPatient(patient)
                              setIsVisionFormOpen(true)
                            }}
                          >
                            <Pencil className="h-4 w-4" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleDeletePatient(patient.id)}
                          >
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        </div>
                      </div>

                      <Separator />

                      <div className="grid grid-cols-2 gap-4">
                        <div>
                          <p className="text-xs font-medium text-gray-500 mb-2">Œil Droit (OD)</p>
                          <div className="space-y-1 text-sm">
                            <p>Sphère: {patient.odSphere !== null ? patient.odSphere.toFixed(2) : '-'}</p>
                            <p>Cylindre: {patient.odCylindre !== null ? patient.odCylindre.toFixed(2) : '-'}</p>
                            <p>Axe: {patient.odAxe !== null ? `${patient.odAxe}°` : '-'}</p>
                          </div>
                        </div>
                        <div>
                          <p className="text-xs font-medium text-gray-500 mb-2">Œil Gauche (OG)</p>
                          <div className="space-y-1 text-sm">
                            <p>Sphère: {patient.ogSphere !== null ? patient.ogSphere.toFixed(2) : '-'}</p>
                            <p>Cylindre: {patient.ogCylindre !== null ? patient.ogCylindre.toFixed(2) : '-'}</p>
                            <p>Axe: {patient.ogAxe !== null ? `${patient.ogAxe}°` : '-'}</p>
                          </div>
                        </div>
                      </div>

                      {(patient.addition !== null || patient.pd !== null || patient.hauteur !== null) && (
                        <>
                          <Separator />
                          <div className="grid grid-cols-3 gap-4 text-sm">
                            <div>
                              <p className="text-xs font-medium text-gray-500 mb-1">Addition</p>
                              <p>{patient.addition !== null ? patient.addition.toFixed(2) : '-'}</p>
                            </div>
                            <div>
                              <p className="text-xs font-medium text-gray-500 mb-1">DP (mm)</p>
                              <p>{patient.pd !== null ? patient.pd.toFixed(1) : '-'}</p>
                            </div>
                            <div>
                              <p className="text-xs font-medium text-gray-500 mb-1">Hauteur (mm)</p>
                              <p>{patient.hauteur !== null ? patient.hauteur.toFixed(1) : '-'}</p>
                            </div>
                          </div>
                        </>
                      )}

                      {patient.ordonnances && patient.ordonnances.length > 0 && (
                        <>
                          <Separator />
                          <div>
                            <p className="text-xs font-medium text-gray-500 mb-2">Ordonnances</p>
                            <div className="flex flex-wrap gap-2">
                              {patient.ordonnances.map((ord) => (
                                <Badge key={ord.id} variant="outline" className="gap-1">
                                  <FileText className="h-3 w-3" />
                                  {ord.numero}
                                </Badge>
                              ))}
                            </div>
                          </div>
                        </>
                      )}
                    </div>
                  </Card>
                ))}
              </div>
            </ScrollArea>
          )}
        </CardContent>
      </Card>

      {/* Vision Form Dialog */}
      {isVisionFormOpen && (
        <VisionForm
          patient={selectedPatient}
          clientId={client.id}
          onSave={handlePatientSaved}
          onCancel={() => {
            setIsVisionFormOpen(false)
            setSelectedPatient(null)
          }}
        />
      )}
    </div>
  )
}
