'use client'

import { useState, useEffect } from 'react'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog'
import { Badge } from '@/components/ui/badge'
import { ScrollArea } from '@/components/ui/scroll-area'
import {
  Search,
  Plus,
  Eye,
  Pencil,
  Phone,
  Mail,
  MapPin,
  Calendar,
  FileText,
  User
} from 'lucide-react'
import { ClientForm } from './client-form'
import { ClientDetail } from './client-detail'

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
  patients?: Patient[]
}

interface Patient {
  id: 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
  ordonnances?: Ordonnance[]
}

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

export function ClientList() {
  const [clients, setClients] = useState<Client[]>([])
  const [filteredClients, setFilteredClients] = useState<Client[]>([])
  const [searchTerm, setSearchTerm] = useState('')
  const [loading, setLoading] = useState(true)
  const [selectedClient, setSelectedClient] = useState<Client | null>(null)
  const [editingClient, setEditingClient] = useState<Client | null>(null)
  const [isAddDialogOpen, setIsAddDialogOpen] = useState(false)
  const [isDetailDialogOpen, setIsDetailDialogOpen] = useState(false)

  useEffect(() => {
    fetchClients()
  }, [])

  useEffect(() => {
    if (searchTerm === '') {
      setFilteredClients(clients)
    } else {
      const term = searchTerm.toLowerCase()
      const filtered = clients.filter(client =>
        client.nom.toLowerCase().includes(term) ||
        client.prenom.toLowerCase().includes(term) ||
        client.telephone.includes(term) ||
        (client.email && client.email.toLowerCase().includes(term)) ||
        (client.ville && client.ville.toLowerCase().includes(term))
      )
      setFilteredClients(filtered)
    }
  }, [searchTerm, clients])

  const fetchClients = async () => {
    try {
      const response = await fetch('/api/clients')
      if (response.ok) {
        const data = await response.json()
        setClients(data)
        setFilteredClients(data)
      }
    } catch (error) {
      console.error('Error fetching clients:', error)
    } finally {
      setLoading(false)
    }
  }

  const handleClientSaved = async () => {
    setIsAddDialogOpen(false)
    setEditingClient(null)
    await fetchClients()
  }

  const handleViewClient = (client: Client) => {
    console.log('handleViewClient called with:', client.id, client.nom, client.prenom, client)
    // Force dialog to close first if already open with different client
    if (isDetailDialogOpen && selectedClient?.id !== client.id) {
      setIsDetailDialogOpen(false)
      // Small delay to ensure dialog closes
      setTimeout(() => {
        setSelectedClient(client)
        setIsDetailDialogOpen(true)
      }, 50)
    } else {
      setSelectedClient(client)
      setIsDetailDialogOpen(true)
    }
  }

  const handleEditClient = (client: Client) => {
    setEditingClient(client)
    setIsAddDialogOpen(true)
  }

  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
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
        <div>
          <h2 className="text-2xl font-bold text-gray-900">Gestion des Clients</h2>
          <p className="text-sm text-gray-500">
            {clients.length} client{clients.length !== 1 ? 's' : ''} enregistré{clients.length !== 1 ? 's' : ''}
          </p>
        </div>
        <Dialog open={isAddDialogOpen} onOpenChange={setIsAddDialogOpen}>
          <DialogTrigger asChild>
            <Button className="gap-2">
              <Plus className="h-4 w-4" />
              Nouveau Client
            </Button>
          </DialogTrigger>
          <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle>
                {editingClient ? 'Modifier le Client' : 'Nouveau Client'}
              </DialogTitle>
              <DialogDescription>
                {editingClient
                  ? 'Modifiez les informations du client'
                  : 'Remplissez les informations pour créer un nouveau client'}
              </DialogDescription>
            </DialogHeader>
            <ClientForm
              client={editingClient}
              onSave={handleClientSaved}
              onCancel={() => {
                setIsAddDialogOpen(false)
                setEditingClient(null)
              }}
            />
          </DialogContent>
        </Dialog>
      </div>

      {/* Search */}
      <Card>
        <CardContent className="pt-6">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
            <Input
              placeholder="Rechercher par nom, prénom, téléphone, email ou ville..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-10"
            />
          </div>
        </CardContent>
      </Card>

      {/* Clients Table */}
      <Card>
        <CardContent className="p-0">
          <ScrollArea className="h-[600px]">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Client</TableHead>
                  <TableHead>Contact</TableHead>
                  <TableHead>Adresse</TableHead>
                  <TableHead>Naissance</TableHead>
                  <TableHead>Fiches</TableHead>
                  <TableHead className="text-right">Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {loading ? (
                  <TableRow>
                    <TableCell colSpan={6} className="text-center py-8">
                      Chargement...
                    </TableCell>
                  </TableRow>
                ) : filteredClients.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={6} className="text-center py-8">
                      <div className="flex flex-col items-center gap-2">
                        <User className="h-12 w-12 text-gray-400" />
                        <p className="text-gray-500">
                          {searchTerm ? 'Aucun client trouvé' : 'Aucun client enregistré'}
                        </p>
                      </div>
                    </TableCell>
                  </TableRow>
                ) : (
                  filteredClients.map((client) => (
                    <TableRow key={client.id} className="hover:bg-gray-50">
                      <TableCell>
                        <div>
                          <div className="font-medium">
                            {client.prenom} {client.nom}
                          </div>
                          <div className="text-sm text-gray-500">
                            {getAge(client.dateNaissance) !== null && (
                              <span className="mr-2">{getAge(client.dateNaissance)} ans</span>
                            )}
                          </div>
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="space-y-1">
                          {client.email && (
                            <div className="flex items-center gap-2 text-sm">
                              <Mail className="h-3 w-3 text-gray-400" />
                              <span className="truncate max-w-[150px]">{client.email}</span>
                            </div>
                          )}
                          <div className="flex items-center gap-2 text-sm">
                            <Phone className="h-3 w-3 text-gray-400" />
                            <span>{client.telephone}</span>
                          </div>
                        </div>
                      </TableCell>
                      <TableCell>
                        {client.adresse || client.ville || client.codePostal ? (
                          <div className="space-y-1">
                            {client.adresse && (
                              <div className="text-sm text-gray-600 truncate max-w-[150px]">
                                {client.adresse}
                              </div>
                            )}
                            <div className="flex items-center gap-1 text-sm text-gray-500">
                              <MapPin className="h-3 w-3" />
                              <span>
                                {client.codePostal && `${client.codePostal} `}
                                {client.ville}
                              </span>
                            </div>
                          </div>
                        ) : (
                          <span className="text-gray-400 text-sm">Non renseignée</span>
                        )}
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center gap-2 text-sm">
                          <Calendar className="h-3 w-3 text-gray-400" />
                          {formatDate(client.dateNaissance)}
                        </div>
                      </TableCell>
                      <TableCell>
                        <Badge variant="secondary" className="gap-1">
                          <FileText className="h-3 w-3" />
                          {client.patients?.length || 0}
                        </Badge>
                      </TableCell>
                      <TableCell className="text-right">
                        <div className="flex justify-end gap-2">
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleViewClient(client)}
                          >
                            <Eye className="h-4 w-4" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleEditClient(client)}
                          >
                            <Pencil className="h-4 w-4" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </ScrollArea>
        </CardContent>
      </Card>

      {/* Client Detail Dialog */}
      <Dialog open={isDetailDialogOpen} onOpenChange={setIsDetailDialogOpen}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>Détail du Client</DialogTitle>
            <DialogDescription>
              Informations complètes et fiches de vision
            </DialogDescription>
          </DialogHeader>
          {selectedClient && (
            <ClientDetail
              key={selectedClient.id}
              client={selectedClient}
              onClose={() => setIsDetailDialogOpen(false)}
              onUpdate={fetchClients}
            />
          )}
        </DialogContent>
      </Dialog>
    </div>
  )
}
