'use client'

import { useState, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog'
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { ScrollArea } from '@/components/ui/scroll-area'
import {
  Plus,
  FileText,
  Pencil,
  Trash2,
  Upload,
  Download,
  Eye,
} from 'lucide-react'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import * as z from 'zod'

const ordonnanceSchema = z.object({
  numero: z.string().min(1, 'Le numéro est requis'),
  dateEmission: z.string().min(1, 'La date est requise'),
  medecin: z.string().optional(),
  notes: z.string().optional(),
})

type OrdonnanceFormValues = z.infer<typeof ordonnanceSchema>

interface Ordonnance {
  id: string
  patientId: string
  numero: string
  dateEmission: string
  medecin: string | null
  notes: string | null
  createdAt: string
  updatedAt: string
  fichiers?: Fichier[]
}

interface Fichier {
  id: string
  nom: string
  type: string
  url: string
  taille: number
  mimeType: string
  createdAt: string
}

interface OrdonnanceListProps {
  patientId: string
  onUpdate?: () => void
}

export function OrdonnanceList({ patientId, onUpdate }: OrdonnanceListProps) {
  const [ordonnances, setOrdonnances] = useState<Ordonnance[]>([])
  const [editingOrdonnance, setEditingOrdonnance] = useState<Ordonnance | null>(null)
  const [isDialogOpen, setIsDialogOpen] = useState(false)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    fetchOrdonnances()
  }, [patientId])

  const fetchOrdonnances = async () => {
    try {
      setLoading(true)
      const response = await fetch(`/api/patients/${patientId}/ordonnances`)
      if (response.ok) {
        const data = await response.json()
        setOrdonnances(data)
      }
    } catch (error) {
      console.error('Error fetching ordonnances:', error)
    } finally {
      setLoading(false)
    }
  }

  const form = useForm<OrdonnanceFormValues>({
    resolver: zodResolver(ordonnanceSchema),
    defaultValues: {
      numero: '',
      dateEmission: new Date().toISOString().split('T')[0],
      medecin: '',
      notes: '',
    },
  })

  const onSubmit = async (data: OrdonnanceFormValues) => {
    try {
      const url = editingOrdonnance
        ? `/api/ordonnances/${editingOrdonnance.id}`
        : '/api/ordonnances'
      const method = editingOrdonnance ? 'PUT' : 'POST'

      const response = await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          ...data,
          patientId,
          medecin: data.medecin || null,
          notes: data.notes || null,
        }),
      })

      if (response.ok) {
        setIsDialogOpen(false)
        setEditingOrdonnance(null)
        form.reset()
        await fetchOrdonnances()
        onUpdate?.()
      } else {
        alert('Erreur lors de la sauvegarde de l\'ordonnance')
      }
    } catch (error) {
      console.error('Error saving ordonnance:', error)
      alert('Erreur lors de la sauvegarde de l\'ordonnance')
    }
  }

  const handleDelete = async (ordonnanceId: string) => {
    if (!confirm('Êtes-vous sûr de vouloir supprimer cette ordonnance ?')) {
      return
    }

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

      if (response.ok) {
        await fetchOrdonnances()
        onUpdate?.()
      } else {
        alert('Erreur lors de la suppression de l\'ordonnance')
      }
    } catch (error) {
      console.error('Error deleting ordonnance:', error)
      alert('Erreur lors de la suppression de l\'ordonnance')
    }
  }

  const handleEdit = (ordonnance: Ordonnance) => {
    setEditingOrdonnance(ordonnance)
    form.reset({
      numero: ordonnance.numero,
      dateEmission: ordonnance.dateEmission.split('T')[0],
      medecin: ordonnance.medecin || '',
      notes: ordonnance.notes || '',
    })
    setIsDialogOpen(true)
  }

  const handleNew = () => {
    setEditingOrdonnance(null)
    form.reset({
      numero: '',
      dateEmission: new Date().toISOString().split('T')[0],
      medecin: '',
      notes: '',
    })
    setIsDialogOpen(true)
  }

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

  const formatFileSize = (bytes: number) => {
    if (bytes === 0) return '0 Bytes'
    const k = 1024
    const sizes = ['Bytes', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i]
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h3 className="text-lg font-semibold flex items-center gap-2">
          <FileText className="h-5 w-5" />
          Ordonnances
          <Badge variant="secondary">{ordonnances.length}</Badge>
        </h3>
        <Button size="sm" onClick={handleNew}>
          <Plus className="h-4 w-4 mr-2" />
          Nouvelle Ordonnance
        </Button>
      </div>

      {loading ? (
        <p className="text-center text-gray-500 py-4">Chargement...</p>
      ) : ordonnances.length === 0 ? (
        <Card>
          <CardContent className="py-8 text-center">
            <FileText className="h-12 w-12 text-gray-400 mx-auto mb-2" />
            <p className="text-gray-500">Aucune ordonnance enregistrée</p>
          </CardContent>
        </Card>
      ) : (
        <div className="space-y-3">
          {ordonnances.map((ordonnance) => (
            <Card key={ordonnance.id}>
              <CardContent className="pt-6">
                <div className="space-y-3">
                  <div className="flex items-start justify-between">
                    <div className="space-y-1">
                      <div className="flex items-center gap-2">
                        <Badge variant="outline">{ordonnance.numero}</Badge>
                        <span className="text-sm text-gray-500">
                          {formatDate(ordonnance.dateEmission)}
                        </span>
                      </div>
                      {ordonnance.medecin && (
                        <p className="text-sm text-gray-600">
                          Médecin: {ordonnance.medecin}
                        </p>
                      )}
                    </div>
                    <div className="flex gap-2">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleEdit(ordonnance)}
                      >
                        <Pencil className="h-4 w-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleDelete(ordonnance.id)}
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </div>
                  </div>

                  {ordonnance.notes && (
                    <p className="text-sm text-gray-600 bg-gray-50 p-2 rounded">
                      {ordonnance.notes}
                    </p>
                  )}

                  {ordonnance.fichiers && ordonnance.fichiers.length > 0 && (
                    <div>
                      <p className="text-xs font-medium text-gray-500 mb-2">Documents joints</p>
                      <div className="flex flex-wrap gap-2">
                        {ordonnance.fichiers.map((fichier) => (
                          <Badge key={fichier.id} variant="secondary" className="gap-1">
                            <FileText className="h-3 w-3" />
                            {fichier.nom}
                            <span className="text-xs text-gray-500">
                              ({formatFileSize(fichier.taille)})
                            </span>
                          </Badge>
                        ))}
                      </div>
                    </div>
                  )}
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}

      {/* Add/Edit Dialog */}
      <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <DialogContent className="max-w-lg">
          <DialogHeader>
            <DialogTitle>
              {editingOrdonnance ? 'Modifier l\'Ordonnance' : 'Nouvelle Ordonnance'}
            </DialogTitle>
            <DialogDescription>
              Enregistrez les informations de l'ordonnance médicale
            </DialogDescription>
          </DialogHeader>
          <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
              <FormField
                control={form.control}
                name="numero"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Numéro *</FormLabel>
                    <FormControl>
                      <Input placeholder="ORD-2024-001" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="dateEmission"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Date d'émission *</FormLabel>
                    <FormControl>
                      <Input type="date" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="medecin"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Médecin</FormLabel>
                    <FormControl>
                      <Input placeholder="Dr. Martin" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="notes"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Notes</FormLabel>
                    <FormControl>
                      <Textarea
                        placeholder="Notes supplémentaires..."
                        className="min-h-[80px]"
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <div className="flex justify-end gap-3 pt-4">
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => setIsDialogOpen(false)}
                >
                  Annuler
                </Button>
                <Button type="submit">
                  {editingOrdonnance ? 'Mettre à jour' : 'Créer'}
                </Button>
              </div>
            </form>
          </Form>
        </DialogContent>
      </Dialog>
    </div>
  )
}
