'use client'

import { useState } from 'react'
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Separator } from "@/components/ui/separator"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { ChevronLeft, Download, Plus, CreditCard } from 'lucide-react'
import Link from 'next/link'

export function BlockPage() {
  const [paymentMethods, setPaymentMethods] = useState([
    {
      id: '1',
      type: 'Visa',
      last4: '4242',
      expiry: '12/2024',
      isDefault: true
    },
    {
      id: '2',
      type: 'Mastercard',
      last4: '5678',
      expiry: '06/2025',
      isDefault: false
    }
  ])

  const [selectedInvoice, setSelectedInvoice] = useState<null | {
    id: string;
    date: string;
    amount: string;
    description: string;
  }>(null)

  const [isEditingCard, setIsEditingCard] = useState<false | string>(false)
  const [isAddingCard, setIsAddingCard] = useState(false)
  const [newCardDetails, setNewCardDetails] = useState({
    cardNumber: '',
    expiryDate: '',
    cvv: ''
  })

  const upcomingInspections = [
    { date: '15/06/2023', amount: '€180.00', description: 'État des lieux d\'entrée - Appartement Paris', icon: '🏢' },
    { date: '01/07/2023', amount: '€220.00', description: 'Inspection de conformité - Local commercial Bordeaux', icon: '🏪' },
    { date: '15/07/2023', amount: '€250.00', description: 'Inspection avant achat - Villa Côte d\'Azur', icon: '🏡' },
  ]

  const paymentHistory = [
    { id: 'INV-001', date: '15/03/2023', amount: '€250.00', description: 'Inspection avant achat - Villa Côte d\'Azur', status: 'Payée', icon: '🏡' },
    { id: 'INV-002', date: '01/04/2023', amount: '€220.00', description: 'Inspection de conformité - Local commercial Bordeaux', status: 'Payée', icon: '🏪' },
    { id: 'INV-003', date: '15/05/2023', amount: '€180.00', description: 'État des lieux d\'entrée - Appartement Paris', status: 'Payée', icon: '🏢' },
  ]

  const handleUpdateCard = () => {
    if (isEditingCard !== false) {
      setPaymentMethods(paymentMethods.map(method => 
        method.id === isEditingCard 
          ? { ...method, last4: newCardDetails.cardNumber.slice(-4), expiry: newCardDetails.expiryDate }
          : method
      ))
      setIsEditingCard(false)
      setNewCardDetails({ cardNumber: '', expiryDate: '', cvv: '' })
    }
  }

  const handleAddCard = () => {
    // Logique pour ajouter une nouvelle carte
    setPaymentMethods([...paymentMethods, {
      id: `${paymentMethods.length + 1}`,
      type: 'Visa', // À déterminer en fonction du numéro de carte
      last4: newCardDetails.cardNumber.slice(-4),
      expiry: newCardDetails.expiryDate,
      isDefault: false
    }])
    setIsAddingCard(false)
  }

  const setDefaultCard = (id: string) => {
    setPaymentMethods(paymentMethods.map(method => ({
      ...method,
      isDefault: method.id === id
    })))
  }

  const deleteCard = (id: string) => {
    setPaymentMethods(paymentMethods.filter(method => method.id !== id))
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="sticky top-0 z-10 bg-white px-4 py-3 shadow-sm">
        <div className="flex items-center justify-between max-w-md mx-auto">
          <Link href="/settings">
            <Button variant="ghost" size="icon" className="text-gray-600 hover:text-gray-900">
              <ChevronLeft className="h-5 w-5" />
              <span className="sr-only">Retour</span>
            </Button>
          </Link>
          <h1 className="text-lg font-semibold text-gray-900">Facturation</h1>
          <div className="w-8"></div>
        </div>
      </div>

      <div className="p-4 max-w-md mx-auto space-y-3">
        <Card className="bg-white shadow-sm">
          <CardHeader className="py-2 px-4">
            <CardTitle className="text-base font-semibold text-gray-900">Méthodes de paiement</CardTitle>
          </CardHeader>
          <CardContent className="pt-0 px-4 pb-4 space-y-2">
            {paymentMethods.map((method, index) => (
              <div key={method.id} className="py-3">
                <div className="flex items-center justify-between">
                  <div className="flex items-center space-x-3">
                    <div className="w-10 h-6 bg-purple-100 rounded-lg flex items-center justify-center">
                      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" className="text-purple-600">
                        <rect x="2" y="6" width="20" height="12" rx="2" className="stroke-current" strokeWidth="2"/>
                        <path d="M2 10H22" className="stroke-current" strokeWidth="2"/>
                      </svg>
                    </div>
                    <div>
                      <p className="text-sm font-medium text-gray-900">{method.type} se terminant par {method.last4}</p>
                      <div className="flex items-center space-x-1">
                        <p className="text-xs text-gray-500">Expire le {method.expiry}</p>
                        {method.isDefault && <span className="text-xs text-gray-500">(Par défaut)</span>}
                      </div>
                    </div>
                  </div>
                  <div className="flex items-center space-x-2">
                    <Button 
                      variant="outline" 
                      size="sm" 
                      className="text-purple-600 border-purple-200 hover:bg-purple-50"
                      onClick={() => setIsEditingCard(method.id)}
                    >
                      Modifier
                    </Button>
                  </div>
                </div>
                {index < paymentMethods.length - 1 && <Separator className="mt-3" />}
              </div>
            ))}
            <Button 
              variant="outline" 
              size="sm" 
              className="mt-4 w-full text-purple-600 border-purple-200 hover:bg-purple-50"
              onClick={() => setIsAddingCard(true)}
            >
              <Plus className="h-4 w-4 mr-2" />
              Ajouter une carte
            </Button>
          </CardContent>
        </Card>

        <Card className="bg-white shadow-sm">
          <CardHeader className="py-2">
            <CardTitle className="text-base font-semibold text-gray-900">Prochaines inspections</CardTitle>
          </CardHeader>
          <CardContent className="pt-0 px-4 pb-4">
            {upcomingInspections.map((inspection, index) => (
              <div key={index} className="relative">
                <div className="flex items-center justify-between p-4">
                  <div className="flex items-center space-x-3">
                    <span className="text-xl">{inspection.icon}</span>
                    <div>
                      <p className="text-sm font-medium text-gray-900">{inspection.date}</p>
                      <p className="text-xs text-gray-500">{inspection.description}</p>
                    </div>
                  </div>
                  <p className="text-sm font-semibold text-gray-900">{inspection.amount}</p>
                </div>
                {index < upcomingInspections.length - 1 && <Separator className="absolute left-4 right-4 bottom-0" />}
              </div>
            ))}
          </CardContent>
        </Card>

        <Card className="bg-white shadow-sm">
          <CardHeader className="py-2">
            <CardTitle className="text-base font-semibold text-gray-900">Historique des paiements</CardTitle>
          </CardHeader>
          <CardContent className="pt-0 px-4 pb-4">
            {paymentHistory.map((payment, index) => (
              <div key={payment.id} className="relative">
                <div className="flex items-center justify-between p-4">
                  <div className="flex items-center space-x-3">
                    <span className="text-xl">{payment.icon}</span>
                    <div>
                      <p className="text-sm font-medium text-gray-900">{payment.date}</p>
                      <p className="text-xs text-gray-500">{payment.description}</p>
                    </div>
                  </div>
                  <div className="flex items-center space-x-3">
                    <div className="text-right">
                      <p className="text-sm font-semibold text-gray-900">{payment.amount}</p>
                      <p className="text-xs text-green-600">{payment.status}</p>
                    </div>
                    <Button 
                      variant="ghost" 
                      size="icon" 
                      className="h-8 w-8"
                      onClick={() => setSelectedInvoice(payment)}
                    >
                      <Download className="h-4 w-4 text-gray-500" />
                      <span className="sr-only">Télécharger la facture</span>
                    </Button>
                  </div>
                </div>
                {index < paymentHistory.length - 1 && <Separator className="absolute left-4 right-4 bottom-0" />}
              </div>
            ))}
          </CardContent>
        </Card>

        <Dialog open={!!selectedInvoice} onOpenChange={() => setSelectedInvoice(null)}>
          <DialogContent className="sm:max-w-md">
            <DialogHeader>
              <DialogTitle>Facture {selectedInvoice?.id}</DialogTitle>
            </DialogHeader>
            {selectedInvoice && (
              <div className="space-y-4">
                <div className="space-y-2">
                  <p className="text-sm font-medium text-gray-900">Date: {selectedInvoice.date}</p>
                  <p className="text-sm text-gray-600">{selectedInvoice.description}</p>
                  <p className="text-lg font-semibold text-gray-900">{selectedInvoice.amount}</p>
                </div>
                <Button 
                  className="w-full bg-purple-600 hover:bg-purple-700 text-white"
                  onClick={() => {
                    console.log('Téléchargement de la facture:', selectedInvoice.id)
                    setSelectedInvoice(null)
                  }}
                >
                  Télécharger la facture
                </Button>
              </div>
            )}
          </DialogContent>
        </Dialog>

        <Dialog open={isEditingCard !== false} onOpenChange={() => setIsEditingCard(false)}>
          <DialogContent className="sm:max-w-md">
            <DialogHeader>
              <DialogTitle>Gérer la carte bancaire</DialogTitle>
            </DialogHeader>
            <div className="space-y-4 py-4">
              {isEditingCard !== false && (
                <>
                  <p className="text-sm text-gray-500">
                    Carte {paymentMethods.find(m => m.id === isEditingCard)?.type} se terminant par {paymentMethods.find(m => m.id === isEditingCard)?.last4}
                  </p>
                  <div className="space-y-4">
                    <div className="space-y-2">
                      <Label htmlFor="cardNumber">Numéro de carte</Label>
                      <Input 
                        id="cardNumber" 
                        placeholder="1234 5678 9012 3456" 
                        value={newCardDetails.cardNumber}
                        onChange={(e) => setNewCardDetails({...newCardDetails, cardNumber: e.target.value})}
                      />
                    </div>
                    <div className="grid grid-cols-2 gap-4">
                      <div className="space-y-2">
                        <Label htmlFor="expiryDate">Date d'expiration</Label>
                        <Input 
                          id="expiryDate" 
                          placeholder="MM/AA" 
                          value={newCardDetails.expiryDate}
                          onChange={(e) => setNewCardDetails({...newCardDetails, expiryDate: e.target.value})}
                        />
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="cvv">CVV</Label>
                        <Input 
                          id="cvv" 
                          placeholder="123" 
                          value={newCardDetails.cvv}
                          onChange={(e) => setNewCardDetails({...newCardDetails, cvv: e.target.value})}
                        />
                      </div>
                    </div>
                    <Button 
                      className="w-full bg-purple-600 hover:bg-purple-700 text-white"
                      onClick={handleUpdateCard}
                    >
                      Mettre à jour la carte
                    </Button>
                  </div>
                  {!paymentMethods.find(m => m.id === isEditingCard)?.isDefault && (
                    <div className="flex justify-between mt-4">
                      <Button 
                        variant="outline" 
                        size="sm" 
                        className="text-purple-600 border-purple-200 hover:bg-purple-50"
                        onClick={() => {
                          setDefaultCard(isEditingCard as string)
                          setIsEditingCard(false)
                        }}
                      >
                        Définir par défaut
                      </Button>
                      <Button 
                        variant="outline" 
                        size="sm" 
                        className="text-red-600 border-red-200 hover:bg-red-50"
                        onClick={() => {
                          deleteCard(isEditingCard as string)
                          setIsEditingCard(false)
                        }}
                      >
                        Supprimer
                      </Button>
                    </div>
                  )}
                </>
              )}
            </div>
          </DialogContent>
        </Dialog>

        <Dialog open={isAddingCard} onOpenChange={setIsAddingCard}>
          <DialogContent className="sm:max-w-md">
            <DialogHeader>
              <DialogTitle>Ajouter une nouvelle carte</DialogTitle>
            </DialogHeader>
            <div className="space-y-4 py-4">
              <div className="space-y-2">
                <Label htmlFor="newCardNumber">Numéro de carte</Label>
                <Input 
                  id="newCardNumber" 
                  placeholder="1234 5678 9012 3456" 
                  value={newCardDetails.cardNumber}
                  onChange={(e) => setNewCardDetails({...newCardDetails, cardNumber: e.target.value})}
                />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="newExpiryDate">Date d'expiration</Label>
                  <Input 
                    id="newExpiryDate" 
                    placeholder="MM/AA" 
                    value={newCardDetails.expiryDate}
                    onChange={(e) => setNewCardDetails({...newCardDetails, expiryDate: e.target.value})}
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="newCvv">CVV</Label>
                  <Input 
                    id="newCvv" 
                    placeholder="123" 
                    value={newCardDetails.cvv}
                    onChange={(e) => setNewCardDetails({...newCardDetails, cvv: e.target.value})}
                  />
                </div>
              </div>
            </div>
            <Button 
              className="w-full bg-purple-600 hover:bg-purple-700 text-white"
              onClick={handleAddCard}
            >
              Ajouter la carte
            </Button>
          </DialogContent>
        </Dialog>
      </div>
    </div>
  )
}