import { useState, useRef } from 'react'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { MoreHorizontal, Trash2, Upload, Download, User as UserIcon } from "lucide-react"
import { useContacts, useDeleteContact, useImportContacts } from "../hooks/useContacts"
import { contactService } from "@/services/contactService"
import type { Contact } from "@/types/api"
import { showConfirm, showToast } from "@/lib/sweetalert"

export function ContactList() {
  const [selectedContact, setSelectedContact] = useState<Contact | undefined>(undefined)
  const [isViewOpen, setIsViewOpen] = useState(false)
  const fileInputRef = useRef<HTMLInputElement>(null)

  const { data, isLoading, isError } = useContacts()
  const deleteContact = useDeleteContact()
  const importContacts = useImportContacts()

  const handleDelete = async (id: string) => {
    const confirmed = await showConfirm(
      "Kişiyi Sil?",
      "Bu kişiyi silmek istediğinize emin misiniz?",
      "Evet, Sil"
    )
    if (confirmed) {
      deleteContact.mutate(id, {
        onSuccess: () => showToast("Kişi başarıyla silindi.", "success"),
        onError: () => showToast("Silme işlemi başarısız.", "error")
      })
    }
  }

  const handleExport = async () => {
    try {
      const blob = await contactService.exportCsv()
      const url = window.URL.createObjectURL(new Blob([blob]))
      const link = document.createElement('a')
      link.href = url
      link.setAttribute('download', 'contacts.csv')
      document.body.appendChild(link)
      link.click()
      link.parentNode?.removeChild(link)
      showToast("CSV dışa aktarıldı.", "success")
    } catch (error) {
      console.error(error)
      showToast("Dışa aktarma başarısız.", "error")
    }
  }

  const handleImportClick = () => {
    fileInputRef.current?.click()
  }

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (file) {
      importContacts.mutate(file, {
        onSuccess: () => showToast("Kişiler başarıyla içe aktarıldı.", "success"),
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        onError: (error: any) => showToast(error.response?.data?.message || "İçe aktarma başarısız.", "error")
      })
    }
    // Reset input
    event.target.value = ''
  }

  const openViewModal = (contact: Contact) => {
    setSelectedContact(contact)
    setIsViewOpen(true)
  }

  if (isLoading) return <div>Yükleniyor...</div>
  if (isError) return <div>Hata oluştu.</div>

  // Handle paginated response structure: { data: Contact[], limit, page, total }
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const contacts: Contact[] = Array.isArray(data) ? data : (data as any)?.data || []

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div className="flex gap-2">
          <input
            type="file"
            ref={fileInputRef}
            className="hidden"
            accept=".csv"
            onChange={handleFileChange}
          />
          <Button variant="outline" size="sm" onClick={handleImportClick} disabled={importContacts.isPending}>
            <Upload className="mr-2 h-4 w-4" />
            {importContacts.isPending ? "Yükleniyor..." : "İçe Aktar (CSV)"}
          </Button>
          <Button variant="outline" size="sm" onClick={handleExport}>
            <Download className="mr-2 h-4 w-4" /> Dışa Aktar
          </Button>
        </div>
      </div>

      <div className="rounded-md border bg-white dark:bg-gray-800">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>İsim</TableHead>
              <TableHead>Konu</TableHead>
              <TableHead>E-posta</TableHead>
              <TableHead>Telefon</TableHead>
              <TableHead>Etiketler</TableHead>
              <TableHead>Durum</TableHead>
              <TableHead className="text-right">İşlemler</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {contacts.length === 0 ? (
              <TableRow>
                <TableCell colSpan={7} className="text-center py-8 text-muted-foreground">
                  Kayıtlı kişi bulunamadı.
                </TableCell>
              </TableRow>
            ) : (
              contacts.map((contact) => (
                <TableRow key={contact.id}>
                  <TableCell className="font-medium flex items-center gap-2">
                    <UserIcon className="w-4 h-4 text-gray-500" />
                    {contact.name}
                  </TableCell>
                  <TableCell>{contact.subject || "-"}</TableCell>
                  <TableCell>{contact.email}</TableCell>
                  <TableCell>{contact.phone || "-"}</TableCell>
                  <TableCell>
                    <div className="flex flex-wrap gap-1">
                      {contact.tags && contact.tags.length > 0 ? (
                        contact.tags.map(tag => (
                          <Badge key={tag.id} variant="secondary" className="text-xs">
                            {tag.tag}
                          </Badge>
                        ))
                      ) : (
                        <span className="text-xs text-muted-foreground">-</span>
                      )}
                    </div>
                  </TableCell>
                  <TableCell>
                    {contact.is_active ? (
                      <Badge className="bg-green-600 hover:bg-green-700">Aktif</Badge>
                    ) : (
                      <Badge variant="secondary">Pasif</Badge>
                    )}
                  </TableCell>
                  <TableCell className="text-right">
                    <DropdownMenu>
                      <DropdownMenuTrigger asChild>
                        <Button variant="ghost" className="h-8 w-8 p-0">
                          <span className="sr-only">Menü</span>
                          <MoreHorizontal className="h-4 w-4" />
                        </Button>
                      </DropdownMenuTrigger>
                      <DropdownMenuContent align="end">
                        <DropdownMenuLabel>İşlemler</DropdownMenuLabel>
                        <DropdownMenuItem onClick={() => openViewModal(contact)}>
                          <Upload className="mr-2 h-4 w-4 rotate-90" /> Görüntüle
                        </DropdownMenuItem>
                        <DropdownMenuSeparator />
                        <DropdownMenuItem onClick={() => handleDelete(contact.id)} className="text-red-600 focus:text-red-600">
                          <Trash2 className="mr-2 h-4 w-4" /> Sil
                        </DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      {/* View Details Dialog */}
      <Dialog open={isViewOpen} onOpenChange={setIsViewOpen}>
        <DialogContent className="sm:max-w-[600px]">
          <DialogHeader>
            <DialogTitle>Kişi Detayları</DialogTitle>
          </DialogHeader>
          {selectedContact && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <h4 className="text-sm font-medium text-gray-500">İsim</h4>
                  <p>{selectedContact.name}</p>
                </div>
                <div>
                  <h4 className="text-sm font-medium text-gray-500">E-posta</h4>
                  <p>{selectedContact.email}</p>
                </div>
                <div>
                  <h4 className="text-sm font-medium text-gray-500">Telefon</h4>
                  <p>{selectedContact.phone || "-"}</p>
                </div>
                <div>
                  <h4 className="text-sm font-medium text-gray-500">Konu</h4>
                  <p>{selectedContact.subject || "-"}</p>
                </div>
                <div>
                  <h4 className="text-sm font-medium text-gray-500">IP Adresi</h4>
                  <p>{selectedContact.ip || "-"}</p>
                </div>
                <div>
                  <h4 className="text-sm font-medium text-gray-500">Oluşturulma</h4>
                  <p>{new Date(selectedContact.created_at).toLocaleString('tr-TR')}</p>
                </div>
              </div>
              <div>
                <h4 className="text-sm font-medium text-gray-500">Mesaj</h4>
                <div className="mt-1 p-3 bg-gray-50 dark:bg-gray-900 rounded-md text-sm whitespace-pre-wrap">
                  {selectedContact.message || "Mesaj yok."}
                </div>
              </div>
              <div>
                <h4 className="text-sm font-medium text-gray-500">Etiketler</h4>
                <div className="flex flex-wrap gap-1 mt-1">
                  {selectedContact.tags && selectedContact.tags.length > 0 ? (
                    selectedContact.tags.map(tag => (
                      <Badge key={tag.id} variant="secondary">
                        {tag.tag}
                      </Badge>
                    ))
                  ) : (
                    <span className="text-sm text-gray-500">-</span>
                  )}
                </div>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  )
}
