"use client"

import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog"
import { Search, MoreHorizontal, Edit, Trash2, Mail, Phone, CreditCard } from "lucide-react"
import type { Client } from "@/types/business"

interface ClientsTableProps {
  clients: Client[]
  onEdit: (client: Client) => void
  onDelete: (clientId: string) => void
  onAddPayment: (clientId: string) => void
}

export function ClientsTable({ clients, onEdit, onDelete, onAddPayment }: ClientsTableProps) {
  const [searchTerm, setSearchTerm] = useState("")
  const [deleteClient, setDeleteClient] = useState<Client | null>(null)

  const filteredClients = clients.filter(
    (client) =>
      client.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      client.email.toLowerCase().includes(searchTerm.toLowerCase()) ||
      client.contactPerson.toLowerCase().includes(searchTerm.toLowerCase()) ||
      client.businessType.toLowerCase().includes(searchTerm.toLowerCase()),
  )

  const getCreditStatus = (outstandingAmount: number, creditLimit: number) => {
    if (outstandingAmount === 0) return { label: "Good Standing", variant: "default" as const, color: "text-green-600" }
    if (outstandingAmount >= creditLimit * 0.9)
      return { label: "Near Limit", variant: "secondary" as const, color: "text-yellow-600" }
    if (outstandingAmount > creditLimit)
      return { label: "Over Limit", variant: "destructive" as const, color: "text-red-600" }
    return { label: "Active Credit", variant: "secondary" as const, color: "text-blue-600" }
  }

  const handleDelete = (client: Client) => {
    onDelete(client.id)
    setDeleteClient(null)
  }

  return (
    <div className="space-y-4">
      {/* Search */}
      <div className="relative">
        <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4" />
        <Input
          placeholder="Search clients by name, email, contact person, or business type..."
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
          className="pl-10"
        />
      </div>

      {/* Clients Table */}
      <div className="border rounded-lg overflow-hidden">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Client</TableHead>
              <TableHead>Contact</TableHead>
              <TableHead>Business Type</TableHead>
              <TableHead>Payment Terms</TableHead>
              <TableHead>Credit Status</TableHead>
              <TableHead>Outstanding</TableHead>
              <TableHead className="w-[50px]"></TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {filteredClients.length === 0 ? (
              <TableRow>
                <TableCell colSpan={7} className="text-center py-8 text-muted-foreground">
                  {searchTerm ? "No clients found matching your search." : "No clients added yet."}
                </TableCell>
              </TableRow>
            ) : (
              filteredClients.map((client) => {
                const creditStatus = getCreditStatus(client.outstandingAmount, client.creditLimit)
                const creditUtilization =
                  client.creditLimit > 0 ? ((client.outstandingAmount / client.creditLimit) * 100).toFixed(1) : "0"

                return (
                  <TableRow key={client.id}>
                    <TableCell>
                      <div>
                        <p className="font-medium">{client.name}</p>
                        {client.contactPerson && (
                          <p className="text-sm text-muted-foreground">{client.contactPerson}</p>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="space-y-1">
                        {client.email && (
                          <div className="flex items-center gap-1 text-sm">
                            <Mail className="h-3 w-3" />
                            <span className="truncate max-w-[150px]">{client.email}</span>
                          </div>
                        )}
                        {client.phone && (
                          <div className="flex items-center gap-1 text-sm">
                            <Phone className="h-3 w-3" />
                            <span>{client.phone}</span>
                          </div>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>
                      <span className="text-sm">{client.businessType || "N/A"}</span>
                    </TableCell>
                    <TableCell>
                      <Badge variant="outline" className="text-xs">
                        {client.paymentTerms}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <div>
                        <Badge variant={creditStatus.variant} className="text-xs mb-1">
                          {creditStatus.label}
                        </Badge>
                        {client.creditLimit > 0 && (
                          <p className="text-xs text-muted-foreground">{creditUtilization}% utilized</p>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="text-right">
                        <p className={`font-medium text-sm ${client.outstandingAmount > 0 ? creditStatus.color : ""}`}>
                          ${client.outstandingAmount.toFixed(2)}
                        </p>
                        <p className="text-xs text-muted-foreground">/ ${client.creditLimit.toFixed(2)} limit</p>
                      </div>
                    </TableCell>
                    <TableCell>
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button variant="ghost" size="sm">
                            <MoreHorizontal className="h-4 w-4" />
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end">
                          <DropdownMenuItem onClick={() => onEdit(client)}>
                            <Edit className="h-4 w-4 mr-2" />
                            Edit
                          </DropdownMenuItem>
                          <DropdownMenuItem onClick={() => onAddPayment(client.id)}>
                            <CreditCard className="h-4 w-4 mr-2" />
                            Add Payment
                          </DropdownMenuItem>
                          <DropdownMenuItem onClick={() => setDeleteClient(client)} className="text-red-600">
                            <Trash2 className="h-4 w-4 mr-2" />
                            Delete
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </TableCell>
                  </TableRow>
                )
              })
            )}
          </TableBody>
        </Table>
      </div>

      {/* Delete Confirmation Dialog */}
      <AlertDialog open={!!deleteClient} onOpenChange={() => setDeleteClient(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete Client</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to delete "{deleteClient?.name}"? This action cannot be undone and will remove all
              associated transaction history.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={() => deleteClient && handleDelete(deleteClient)}
              className="bg-red-600 hover:bg-red-700"
            >
              Delete
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  )
}
