'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Label } from "@/components/ui/label"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog"
import { Separator } from "@/components/ui/separator"
import { ChevronLeft, Upload, Check, X, AlertCircle, Home, MapPin, Ruler, Calendar, Eye, FileText } from 'lucide-react'

type Document = {
  id: string
  name: string
  isRequired: boolean
  isUploaded: boolean
  rejectionReason?: string
}

type Category = {
  name: string
  documents: Document[]
  status: 'pending' | 'validated' | 'rejected'
}

type Property = {
  id: string
  name: string
  address: string
  type: string
  rooms: number
  surface: number
  constructionYear: number
  categories: Category[]
}

export function BlockPage() {
  const router = useRouter()
  
  const [property, setProperty] = useState<Property>({
    id: '1',
    name: 'Appartement Haussmannien',
    address: '15 Avenue des Champs-Élysées, 75008 Paris',
    type: 'Appartement',
    rooms: 4,
    surface: 120,
    constructionYear: 1890,
    categories: [
      {
        name: "Inspection",
        documents: [
          { id: '1', name: "Dernier état des lieux", isRequired: true, isUploaded: true },
          { id: '2', name: "Photos ou vidéos du bien", isRequired: false, isUploaded: true },
          { id: '3', name: "Rapport d'inspection récent", isRequired: true, isUploaded: false },
        ],
        status: 'validated'
      },
      {
        name: "Administratif",
        documents: [
          { id: '4', name: "Contrat de location", isRequired: true, isUploaded: true },
          { id: '5', name: "Attestation d'assurance", isRequired: true, isUploaded: false },
          { id: '6', name: "Diagnostic de performance énergétique", isRequired: true, isUploaded: true },
        ],
        status: 'pending'
      },
      {
        name: "Réparations",
        documents: [
          { id: '7', name: "Factures de rénovation", isRequired: false, isUploaded: true },
          { id: '8', name: "Devis pour travaux futurs", isRequired: false, isUploaded: false, rejectionReason: "Document illisible, veuillez le télécharger à nouveau." },
        ],
        status: 'rejected'
      },
      {
        name: "Copropriété",
        documents: [
          { id: '9', name: "Règlement de copropriété", isRequired: true, isUploaded: true },
          { id: '10', name: "Procès-verbaux des assemblées générales", isRequired: false, isUploaded: false },
        ],
        status: 'pending'
      },
    ]
  })

  const calculateProgress = (category: Category) => {
    const totalDocuments = category.documents.length
    const uploadedDocuments = category.documents.filter(doc => doc.isUploaded).length
    return (uploadedDocuments / totalDocuments) * 100
  }

  const calculateTotalProgress = () => {
    const totalDocuments = property.categories.reduce((sum, category) => sum + category.documents.length, 0)
    const uploadedDocuments = property.categories.reduce((sum, category) => 
      sum + category.documents.filter(doc => doc.isUploaded).length, 0
    )
    return (uploadedDocuments / totalDocuments) * 100
  }

  const handleFileUpload = (categoryIndex: number, documentId: string) => {
    setProperty(prevProperty => {
      const newCategories = [...prevProperty.categories]
      const category = newCategories[categoryIndex]
      if (category) {
        category.documents = category.documents.map(doc => 
          doc.id === documentId ? { ...doc, isUploaded: true, rejectionReason: undefined } : doc
        )
      }
      return { ...prevProperty, categories: newCategories }
    })
  }

  const handleFileRemove = (categoryIndex: number, documentId: string) => {
    setProperty(prevProperty => {
      const newCategories = [...prevProperty.categories]
      const category = newCategories[categoryIndex]
      if (category) {
        category.documents = category.documents.map(doc => 
          doc.id === documentId ? { ...doc, isUploaded: false } : doc
        )
      }
      return { ...prevProperty, categories: newCategories }
    })
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-lg mx-auto p-4">
        <div className="flex items-center justify-between mb-4">
          <button 
            onClick={() => router.back()}
            className="p-2 hover:bg-gray-100 rounded-full transition-colors duration-200"
          >
            <ChevronLeft className="h-5 w-5" />
          </button>
          <h1 className="text-lg font-bold text-center text-gray-800 truncate">{property.name}</h1>
          <div className="w-8" />
        </div>

        <Card className="mb-4 shadow-sm">
          <CardContent className="p-3">
            <div className="grid grid-cols-2 gap-2 text-xs">
              <div className="flex items-center">
                <Home className="h-4 w-4 mr-1 text-[#8B5CF6]" />
                <span className="text-gray-600">{property.type}</span>
              </div>
              <div className="flex items-center">
                <Ruler className="h-4 w-4 mr-1 text-[#8B5CF6]" />
                <span className="text-gray-600">{property.surface} m² - {property.rooms} pièces</span>
              </div>
              <div className="flex items-center">
                <MapPin className="h-4 w-4 mr-1 text-[#8B5CF6] flex-shrink-0" />
                <span className="text-gray-600 truncate">{property.address}</span>
              </div>
              <div className="flex items-center">
                <Calendar className="h-4 w-4 mr-1 text-[#8B5CF6]" />
                <span className="text-gray-600">Construit en {property.constructionYear}</span>
              </div>
            </div>
          </CardContent>
        </Card>

        <div className="mb-4">
          <div className="flex justify-between items-center mb-1">
            <h2 className="text-sm font-semibold">Progression globale</h2>
            <span className="text-xs font-medium text-gray-600">{Math.round(calculateTotalProgress())}%</span>
          </div>
          <div className="w-full bg-gray-200 rounded-full h-1.5">
            <div 
              className="bg-[#8B5CF6] h-1.5 rounded-full transition-all duration-500 ease-in-out" 
              style={{ width: `${calculateTotalProgress()}%` }}
            />
          </div>
        </div>

        <div className="space-y-4">
          {property.categories.map((category, categoryIndex) => (
            <Card key={category.name} className="shadow-sm overflow-hidden">
              <CardHeader className="bg-gray-50 p-3">
                <div className="flex items-center justify-between">
                  <CardTitle className="text-sm font-semibold">{category.name}</CardTitle>
                  <Badge 
                    variant="outline" 
                    className={
                      category.status === 'validated' ? "bg-green-50 text-green-700 border-green-200" :
                      category.status === 'rejected' ? "bg-red-50 text-red-700 border-red-200" :
                      "bg-yellow-50 text-yellow-700 border-yellow-200"
                    }
                  >
                    {category.status === 'validated' ? 'Validé' :
                     category.status === 'rejected' ? 'Rejeté' : 'En attente'}
                  </Badge>
                </div>
                <div className="mt-2">
                  <div className="flex justify-between items-center mb-1">
                    <span className="text-xs text-gray-600">Progression</span>
                    <span className="text-xs font-medium text-gray-600">{Math.round(calculateProgress(category))}%</span>
                  </div>
                  <div className="w-full bg-gray-200 rounded-full h-1">
                    <div 
                      className="bg-[#8B5CF6] h-1 rounded-full transition-all duration-500 ease-in-out" 
                      style={{ width: `${calculateProgress(category)}%` }}
                    />
                  </div>
                </div>
              </CardHeader>
              <CardContent className="p-0">
                {category.documents.map((doc, index) => (
                  <div key={doc.id}>
                    {index > 0 && <Separator />}
                    <div className="p-3">
                      <div className="flex justify-between items-start mb-2">
                        <div>
                          <Label className="text-sm font-medium text-gray-800">{doc.name}</Label>
                          {doc.isRequired && (
                            <span className="ml-1 text-xs text-red-500 font-medium">Obligatoire</span>
                          )}
                        </div>
                        {doc.isUploaded ? (
                          <span className="text-xs text-green-500 font-medium flex items-center">
                            <Check className="h-3 w-3 mr-1" />
                            Téléchargé
                          </span>
                        ) : (
                          <span className="text-xs text-yellow-500 font-medium flex items-center">
                            <AlertCircle className="h-3 w-3 mr-1" />
                            En attente
                          </span>
                        )}
                      </div>
                      {doc.rejectionReason && (
                        <p className="text-xs text-red-500 mb-2">{doc.rejectionReason}</p>
                      )}
                      <div className="flex items-center space-x-2">
                        {doc.isUploaded ? (
                          <>
                            <Dialog>
                              <DialogTrigger asChild>
                                <Button variant="outline" size="sm" className="h-8 px-2 text-xs">
                                  <Eye className="h-3 w-3 mr-1" />
                                  Voir
                                </Button>
                              </DialogTrigger>
                              <DialogContent className="sm:max-w-[425px]">
                                <DialogHeader>
                                  <DialogTitle>{doc.name}</DialogTitle>
                                </DialogHeader>
                                <div className="flex items-center justify-center p-4 bg-gray-100 rounded-md">
                                  <FileText className="h-24 w-24 text-gray-400" />
                                </div>
                                <p className="text-center text-sm text-gray-500">Aperçu du document</p>
                              </DialogContent>
                            </Dialog>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleFileRemove(categoryIndex, doc.id)}
                              className="h-8 px-2 text-xs"
                            >
                              <X className="h-3 w-3" />
                            </Button>
                          </>
                        ) : (
                          <div className="flex items-center">
                            <Input
                              type="file"
                              className="hidden"
                              id={`file-${doc.id}`}
                              onChange={() => handleFileUpload(categoryIndex, doc.id)}
                            />
                            <Label
                              htmlFor={`file-${doc.id}`}
                              className="cursor-pointer bg-gray-200 hover:bg-gray-300 text-gray-700 py-1 px-3 rounded-lg text-xs flex items-center transition-colors duration-200"
                            >
                              <Upload className="h-3 w-3 mr-1" />
                              Télécharger
                            </Label>
                          </div>
                        )}
                      </div>
                    </div>
                  </div>
                ))}
              </CardContent>
            </Card>
          ))}
        </div>
      </div>
    </div>
  )
}