"use client"

import { AppSidebar } from "@/components/app-sidebar"
import { SiteHeader } from "@/components/site-header"
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar"
import { useRouter } from "next/navigation"
import { useState, useEffect } from "react"
import { Button } from "@/components/ui/button"
import { Card, CardTitle, CardHeader, CardContent } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { useTranslation } from "react-i18next"

export default function DeliveryInvoicePaymentDetailsPage({ params }: { params: { id: string } }) {
  const { id } = params;
  const router = useRouter()
  const [invoice, setInvoice] = useState<any | null>(null)
  const [loading, setLoading] = useState(true)
  const { t } = useTranslation()

  useEffect(() => {
    fetch("/execution-operations/api")
      .then(res => res.json())
      .then((data) => {
        const foundInvoice = data.invoices.find((inv: any) => inv.id === Number(id))
        if (foundInvoice) {
          setInvoice(foundInvoice)
        }
        setLoading(false)
      })
  }, [id])

  const handleBack = () => {
    if (window.history.length > 1) {
      router.back();
    } else {
      router.push("/execution-operations/deliveryinvoicespayments");
    }
  }

  const handleSave = async () => {
    if (!invoice) return;
    try {
      const response = await fetch('/execution-operations/api', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(invoice)
      });
      if (!response.ok) throw new Error('Failed to save changes');
      alert('Payment details saved!');
      router.refresh();
    } catch (error) {
      alert('Failed to save changes.');
    }
  };

  if (loading) {
    return <div>Loading...</div>
  }

  if (!invoice) {
    return <div>Invoice not found</div>
  }

  // Calculate open amount and delay days
  const cashedInValue = parseFloat(invoice[" Cashed in value "]?.replace(/,/g, "") || "0")
  const totalValue = parseFloat(invoice[" Invoice Total Value "]?.replace(/,/g, "") || "0")
  const openAmount = (totalValue - cashedInValue).toLocaleString(undefined, { maximumFractionDigits: 2 })

  let delayDays = "-"
  if (invoice["Invoice due date"] && invoice["Cashed in date"]) {
    const due = new Date(invoice["Invoice due date"])
    const cashed = new Date(invoice["Cashed in date"])
    delayDays = Math.max(0, Math.ceil((cashed.getTime() - due.getTime()) / (1000 * 60 * 60 * 24))).toString()
  }

  return (
    <SidebarProvider
      style={{
        "--sidebar-width": "calc(var(--spacing) * 72)",
        "--header-height": "calc(var(--spacing) * 12)",
      } as React.CSSProperties}
    >
      <AppSidebar variant="inset" />
      <SidebarInset>
        <SiteHeader title="Payment Details" />
        <div className="flex flex-1 flex-col">
          <div className="flex flex-col gap-4 py-4 md:gap-6 md:py-4">
            <div className="flex justify-between items-center px-4 lg:px-6">
              <div className="flex items-center gap-4">
                <h2 className="text-2xl font-bold">Payment Details</h2>
                <Badge variant={openAmount === "0" ? "default" : "destructive"}>
                  {openAmount === "0" ? "Paid" : "Unpaid"}
                </Badge>
              </div>
              <div className="flex gap-2">
                <Button variant="outline" onClick={handleBack}>Back</Button>
                <Button onClick={handleSave}>Save Changes</Button>
              </div>
            </div>
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 px-4 lg:px-6">
              <Card>
                <CardHeader>
                  <CardTitle>Payment Information</CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="grid grid-cols-2 gap-4">
                    <div className="flex flex-col gap-2">
                      <span className="font-medium">Cashed in Date</span>
                      <Input
                        type="date"
                        value={invoice["Cashed in date"] || ""}
                        onChange={e => setInvoice({ ...invoice, "Cashed in date": e.target.value })}
                      />
                    </div>
                    <div className="flex flex-col gap-2">
                      <span className="font-medium">Cashed in Value</span>
                      <Input
                        type="number"
                        value={invoice[" Cashed in value "]?.replace(/,/g, "") || ""}
                        onChange={e => setInvoice({ ...invoice, " Cashed in value ": e.target.value })}
                      />
                    </div>
                    <div className="flex flex-col gap-2">
                      <span className="font-medium">Mentions</span>
                      <Input
                        value={invoice["Mentions"] || ""}
                        onChange={e => setInvoice({ ...invoice, "Mentions": e.target.value })}
                        placeholder="Enter mentions..."
                      />
                    </div>
                  </div>
                </CardContent>
              </Card>
              <Card>
                <CardHeader>
                  <CardTitle>Auto-calculated</CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="flex flex-col gap-2">
                    <span className="font-medium">Open Amount</span>
                    <Input value={openAmount} readOnly />
                  </div>
                  <div className="flex flex-col gap-2">
                    <span className="font-medium">Delay Days</span>
                    <Input value={delayDays} readOnly />
                  </div>
                </CardContent>
              </Card>
            </div>
          </div>
        </div>
      </SidebarInset>
    </SidebarProvider>
  )
} 