"use client"

import { TableCell } from "@/components/ui/table"

import { TableBody } from "@/components/ui/table"

import { TableHead } from "@/components/ui/table"

import { TableRow } from "@/components/ui/table"

import { TableHeader } from "@/components/ui/table"

import { Table } from "@/components/ui/table"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { useToast } from "@/components/ui/use-toast"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Separator } from "@/components/ui/separator"
import {
  ArrowLeft,
  Receipt,
  Building,
  Calendar,
  Download,
  Send,
  FileText,
  CheckCircle,
  Clock,
  AlertCircle,
  Ban,
  Building2,
  Wallet,
} from "lucide-react"
import Link from "next/link"

// Mock data for a single payment
const paymentData = {
  id: "INV-2023-003",
  clearanceId: "CL-2023-003",
  client: "Saudi Logistics",
  clientEmail: "finance@saudilogistics.com",
  clientPhone: "+966 12 345 6789",
  status: "processing",
  amount: 32000.0,
  currency: "SAR",
  date: "2023-12-20",
  dueDate: "2024-01-04",
  paymentMethod: "Bank Transfer",
  description: "Container handling and storage fees",

  // Billing Details
  billingDetails: {
    company: "Saudi Logistics Co.",
    address: "Industrial Area, Building 45",
    city: "Riyadh",
    state: "Riyadh Province",
    country: "Saudi Arabia",
    zipCode: "12345",
    taxId: "300000000000003",
  },

  // Payment Details
  paymentDetails: {
    bankName: "Saudi National Bank",
    accountHolder: "I-Linker Services",
    accountNumber: "SA44 2000 0001 2345 6789 1234",
    swiftCode: "SNBKSARI",
    reference: "REF123456789",
  },

  // Invoice Items
  items: [
    {
      description: "Port Handling Charges",
      quantity: 3,
      unitPrice: 5000.0,
      amount: 15000.0,
    },
    {
      description: "Storage Fees",
      quantity: 10,
      unitPrice: 1000.0,
      amount: 10000.0,
    },
    {
      description: "Documentation Charges",
      quantity: 1,
      unitPrice: 5000.0,
      amount: 5000.0,
    },
    {
      description: "Customs Processing Fee",
      quantity: 1,
      unitPrice: 2000.0,
      amount: 2000.0,
    },
  ],

  // Tax Details
  tax: {
    vatRate: 0.15,
    vatAmount: 4173.91,
    totalWithoutVat: 27826.09,
    totalWithVat: 32000.0,
  },

  // Payment Timeline
  timeline: [
    {
      date: "2023-12-20 09:00",
      status: "Created",
      description: "Invoice generated and sent to client",
    },
    {
      date: "2023-12-20 14:30",
      status: "Sent",
      description: "Payment request sent to client via email",
    },
    {
      date: "2023-12-21 10:15",
      status: "Processing",
      description: "Bank transfer initiated by client",
    },
  ],
}

export default function PaymentDetailPage({ params }: { params: { id: string } }) {
  const router = useRouter()
  const { toast } = useToast()
  const [activeTab, setActiveTab] = useState("details")

  // In a real app, you would fetch the data based on the ID
  const payment = paymentData

  const getStatusBadge = (status: string) => {
    switch (status) {
      case "paid":
        return (
          <Badge variant="outline" className="bg-green-100 text-green-800 hover:bg-green-100">
            Paid
          </Badge>
        )
      case "pending":
        return (
          <Badge variant="outline" className="bg-yellow-100 text-yellow-800 hover:bg-yellow-100">
            Pending
          </Badge>
        )
      case "processing":
        return (
          <Badge variant="outline" className="bg-blue-100 text-blue-800 hover:bg-blue-100">
            Processing
          </Badge>
        )
      case "overdue":
        return (
          <Badge variant="outline" className="bg-red-100 text-red-800 hover:bg-red-100">
            Overdue
          </Badge>
        )
      case "cancelled":
        return (
          <Badge variant="outline" className="bg-gray-100 text-gray-800 hover:bg-gray-100">
            Cancelled
          </Badge>
        )
      default:
        return <Badge variant="outline">{status}</Badge>
    }
  }

  const getStatusIcon = (status: string) => {
    switch (status) {
      case "paid":
        return <CheckCircle className="h-5 w-5 text-green-600" />
      case "pending":
        return <Clock className="h-5 w-5 text-yellow-600" />
      case "processing":
        return <Clock className="h-5 w-5 text-blue-600" />
      case "overdue":
        return <AlertCircle className="h-5 w-5 text-red-600" />
      case "cancelled":
        return <Ban className="h-5 w-5 text-gray-600" />
      default:
        return null
    }
  }

  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat("en-SA", {
      style: "currency",
      currency: payment.currency,
    }).format(amount)
  }

  const handleDownloadInvoice = () => {
    toast({
      title: "Downloading invoice",
      description: "The invoice PDF is being generated and downloaded.",
    })
  }

  const handleSendInvoice = () => {
    toast({
      title: "Invoice sent",
      description: "The invoice has been sent to the client's email.",
    })
  }

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
        <div className="flex items-center gap-2">
          <Link href="/dashboard/payments">
            <Button variant="outline" size="icon">
              <ArrowLeft className="h-4 w-4" />
            </Button>
          </Link>
          <div>
            <h2 className="text-2xl font-bold tracking-tight">Invoice {params.id}</h2>
            <p className="text-muted-foreground">View and manage invoice details</p>
          </div>
        </div>
        <div className="flex flex-wrap gap-2">
          <Button variant="outline" onClick={handleSendInvoice}>
            <Send className="mr-2 h-4 w-4" />
            Send Invoice
          </Button>
          <Button variant="outline" onClick={handleDownloadInvoice}>
            <Download className="mr-2 h-4 w-4" />
            Download PDF
          </Button>
          {payment.status === "paid" && (
            <Button>
              <Receipt className="mr-2 h-4 w-4" />
              View Receipt
            </Button>
          )}
        </div>
      </div>

      <div className="grid gap-6 md:grid-cols-6">
        <Card className="md:col-span-4">
          <CardHeader>
            <div className="flex items-center justify-between">
              <CardTitle>Invoice Details</CardTitle>
              <div className="flex items-center gap-2">
                {getStatusIcon(payment.status)}
                {getStatusBadge(payment.status)}
              </div>
            </div>
            <CardDescription>Complete invoice and payment information</CardDescription>
          </CardHeader>
          <CardContent>
            <Tabs defaultValue="details" value={activeTab} onValueChange={setActiveTab}>
              <TabsList className="mb-4">
                <TabsTrigger value="details">Details</TabsTrigger>
                <TabsTrigger value="items">Items</TabsTrigger>
                <TabsTrigger value="payment">Payment</TabsTrigger>
                <TabsTrigger value="history">History</TabsTrigger>
              </TabsList>

              <TabsContent value="details" className="space-y-6">
                <div className="grid gap-6 md:grid-cols-2">
                  <div>
                    <h3 className="text-lg font-medium flex items-center gap-2">
                      <Building className="h-5 w-5 text-muted-foreground" />
                      Billing Information
                    </h3>
                    <Separator className="my-2" />
                    <dl className="space-y-2 text-sm">
                      <div className="flex justify-between">
                        <dt className="font-medium">Company:</dt>
                        <dd>{payment.billingDetails.company}</dd>
                      </div>
                      <div className="flex justify-between">
                        <dt className="font-medium">Address:</dt>
                        <dd>{payment.billingDetails.address}</dd>
                      </div>
                      <div className="flex justify-between">
                        <dt className="font-medium">City:</dt>
                        <dd>{payment.billingDetails.city}</dd>
                      </div>
                      <div className="flex justify-between">
                        <dt className="font-medium">Country:</dt>
                        <dd>{payment.billingDetails.country}</dd>
                      </div>
                      <div className="flex justify-between">
                        <dt className="font-medium">Tax ID:</dt>
                        <dd>{payment.billingDetails.taxId}</dd>
                      </div>
                    </dl>
                  </div>

                  <div>
                    <h3 className="text-lg font-medium flex items-center gap-2">
                      <Building2 className="h-5 w-5 text-muted-foreground" />
                      Company Information
                    </h3>
                    <Separator className="my-2" />
                    <dl className="space-y-2 text-sm">
                      <div className="flex justify-between">
                        <dt className="font-medium">Company:</dt>
                        <dd>I-Linker Services</dd>
                      </div>
                      <div className="flex justify-between">
                        <dt className="font-medium">Tax Registration:</dt>
                        <dd>310950445300003</dd>
                      </div>
                      <div className="flex justify-between">
                        <dt className="font-medium">Address:</dt>
                        <dd>King Abdullah Port, King Abdullah Economic City</dd>
                      </div>
                      <div className="flex justify-between">
                        <dt className="font-medium">Email:</dt>
                        <dd>billing@ilinker.sa</dd>
                      </div>
                      <div className="flex justify-between">
                        <dt className="font-medium">Phone:</dt>
                        <dd>+966 12 000 0000</dd>
                      </div>
                    </dl>
                  </div>
                </div>

                <div>
                  <h3 className="text-lg font-medium flex items-center gap-2">
                    <Calendar className="h-5 w-5 text-muted-foreground" />
                    Invoice Information
                  </h3>
                  <Separator className="my-2" />
                  <dl className="grid grid-cols-1 md:grid-cols-2 gap-2 text-sm">
                    <div className="flex justify-between">
                      <dt className="font-medium">Invoice Number:</dt>
                      <dd>{payment.id}</dd>
                    </div>
                    <div className="flex justify-between">
                      <dt className="font-medium">Clearance ID:</dt>
                      <dd>{payment.clearanceId}</dd>
                    </div>
                    <div className="flex justify-between">
                      <dt className="font-medium">Issue Date:</dt>
                      <dd>{payment.date}</dd>
                    </div>
                    <div className="flex justify-between">
                      <dt className="font-medium">Due Date:</dt>
                      <dd>{payment.dueDate}</dd>
                    </div>
                    <div className="flex justify-between">
                      <dt className="font-medium">Payment Method:</dt>
                      <dd>{payment.paymentMethod}</dd>
                    </div>
                    <div className="flex justify-between">
                      <dt className="font-medium">Status:</dt>
                      <dd>{payment.status}</dd>
                    </div>
                  </dl>
                </div>
              </TabsContent>

              <TabsContent value="items" className="space-y-6">
                <div className="rounded-md border">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>Description</TableHead>
                        <TableHead className="text-right">Quantity</TableHead>
                        <TableHead className="text-right">Unit Price</TableHead>
                        <TableHead className="text-right">Amount</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {payment.items.map((item, index) => (
                        <TableRow key={index}>
                          <TableCell>{item.description}</TableCell>
                          <TableCell className="text-right">{item.quantity}</TableCell>
                          <TableCell className="text-right">{formatCurrency(item.unitPrice)}</TableCell>
                          <TableCell className="text-right">{formatCurrency(item.amount)}</TableCell>
                        </TableRow>
                      ))}
                      <TableRow>
                        <TableCell colSpan={3} className="text-right font-medium">
                          Subtotal
                        </TableCell>
                        <TableCell className="text-right font-medium">
                          {formatCurrency(payment.tax.totalWithoutVat)}
                        </TableCell>
                      </TableRow>
                      <TableRow>
                        <TableCell colSpan={3} className="text-right font-medium">
                          VAT ({payment.tax.vatRate * 100}%)
                        </TableCell>
                        <TableCell className="text-right font-medium">
                          {formatCurrency(payment.tax.vatAmount)}
                        </TableCell>
                      </TableRow>
                      <TableRow>
                        <TableCell colSpan={3} className="text-right font-medium">
                          Total
                        </TableCell>
                        <TableCell className="text-right font-medium">
                          {formatCurrency(payment.tax.totalWithVat)}
                        </TableCell>
                      </TableRow>
                    </TableBody>
                  </Table>
                </div>
              </TabsContent>

              <TabsContent value="payment" className="space-y-6">
                <div>
                  <h3 className="text-lg font-medium flex items-center gap-2">
                    <Wallet className="h-5 w-5 text-muted-foreground" />
                    Payment Information
                  </h3>
                  <Separator className="my-2" />
                  <dl className="space-y-2 text-sm">
                    <div className="flex justify-between">
                      <dt className="font-medium">Bank Name:</dt>
                      <dd>{payment.paymentDetails.bankName}</dd>
                    </div>
                    <div className="flex justify-between">
                      <dt className="font-medium">Account Holder:</dt>
                      <dd>{payment.paymentDetails.accountHolder}</dd>
                    </div>
                    <div className="flex justify-between">
                      <dt className="font-medium">Account Number (IBAN):</dt>
                      <dd>{payment.paymentDetails.accountNumber}</dd>
                    </div>
                    <div className="flex justify-between">
                      <dt className="font-medium">SWIFT Code:</dt>
                      <dd>{payment.paymentDetails.swiftCode}</dd>
                    </div>
                    <div className="flex justify-between">
                      <dt className="font-medium">Payment Reference:</dt>
                      <dd>{payment.paymentDetails.reference}</dd>
                    </div>
                  </dl>
                </div>

                <div className="rounded-md border p-4 bg-muted/50">
                  <h4 className="font-medium mb-2">Payment Instructions</h4>
                  <ol className="list-decimal list-inside space-y-2 text-sm">
                    <li>Please use the payment reference number in all transactions</li>
                    <li>Ensure the exact amount is transferred to avoid processing delays</li>
                    <li>Send payment confirmation to billing@ilinker.sa</li>
                    <li>Include invoice number in all correspondence</li>
                  </ol>
                </div>
              </TabsContent>

              <TabsContent value="history" className="space-y-6">
                <div>
                  <h3 className="text-lg font-medium flex items-center gap-2">
                    <Clock className="h-5 w-5 text-muted-foreground" />
                    Payment Timeline
                  </h3>
                  <Separator className="my-2" />

                  <div className="relative pl-6 border-l-2 border-muted space-y-6 py-2">
                    {payment.timeline.map((event, index) => (
                      <div key={index} className="relative">
                        <div className="absolute -left-[25px] p-1 rounded-full bg-background border-2 border-muted">
                          {event.status === "Created" && <FileText className="h-4 w-4 text-blue-600" />}
                          {event.status === "Sent" && <Send className="h-4 w-4 text-yellow-600" />}
                          {event.status === "Processing" && <Clock className="h-4 w-4 text-orange-600" />}
                        </div>
                        <div className="bg-muted/50 p-4 rounded-md">
                          <div className="flex items-center justify-between mb-1">
                            <h4 className="font-medium">{event.status}</h4>
                            <span className="text-xs text-muted-foreground">{event.date}</span>
                          </div>
                          <p className="text-sm">{event.description}</p>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              </TabsContent>
            </Tabs>
          </CardContent>
        </Card>

        <Card className="md:col-span-2">
          <CardHeader>
            <CardTitle>Payment Summary</CardTitle>
            <CardDescription>Quick overview and actions</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="space-y-2">
              <h4 className="font-medium">Amount Due</h4>
              <div className="text-3xl font-bold">{formatCurrency(payment.amount)}</div>
              <p className="text-sm text-muted-foreground">Due by {payment.dueDate}</p>
            </div>

            <Separator />

            <div className="space-y-2">
              <h4 className="font-medium">Client Information</h4>
              <div className="text-sm space-y-1">
                <p>{payment.client}</p>
                <p className="text-muted-foreground">{payment.clientEmail}</p>
                <p className="text-muted-foreground">{payment.clientPhone}</p>
              </div>
            </div>

            <Separator />

            <div className="space-y-2">
              <h4 className="font-medium">Quick Actions</h4>
              <div className="grid gap-2">
                <Button variant="outline" className="justify-start" onClick={handleDownloadInvoice}>
                  <Download className="mr-2 h-4 w-4" />
                  Download Invoice
                </Button>
                <Button variant="outline" className="justify-start" onClick={handleSendInvoice}>
                  <Send className="mr-2 h-4 w-4" />
                  Send to Client
                </Button>
                <Button variant="outline" className="justify-start" asChild>
                  <Link href={`/dashboard/clearance/${payment.clearanceId}`}>
                    <FileText className="mr-2 h-4 w-4" />
                    View Clearance
                  </Link>
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  )
}
