"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, useMemo } from "react"
import { Button } from "@/components/ui/button"
import { Card, CardDescription, CardTitle, CardHeader, CardContent, CardFooter } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { IconCircleCheckFilled, IconLoader, IconCircleX, IconPackage } from "@tabler/icons-react"
import { BuildingIcon, DollarIcon } from "@/components/ui/icons"
import { Scale } from "lucide-react"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import React from "react"
import { useTranslation } from "react-i18next"

type Invoice = {
  id: number;
  "Contract number": string;
  "Company": string;
  "Seller Company": string;
  "Buyer Company": string;
  "Goods": string;
  "Basis": string;
  "Basis_1": string;
  "Price per mt": string;
  "Currency": string;
  "Payment Terms": string;
  "Invoice no": string;
  "Invoice date": string;
  "Invoice due date": string;
  " Invoice Quantity ": string;
  " Invoice Price ": string;
  " Invoice Total Value ": string;
  " Invoice Currency ": string;
  " Cashed in value "?: string;
  " Open amount ": string;
  " Invoice saved ": string;
  " Delay days ": string;
  " QTTY CONTRACT ": string;
  "MARGIN": string;
  " QTTY UNDER MARGIN ": string;
  "Details"?: string;
}

export default function InvoiceDetailsPage({ params }: { params: { id: string } }) {
  const { id } = params;
  const router = useRouter()
  const [invoice, setInvoice] = useState<Invoice | null>(null)
  const [loading, setLoading] = useState(true)
  const { t } = useTranslation()
  const [contracts, setContracts] = useState<any[]>([])
  const [selectedContract, setSelectedContract] = useState<any | null>(null)

  useEffect(() => {
    fetch("/execution-operations/api")
      .then(res => res.json())
      .then((data) => {
        const foundInvoice = data.invoices.find((inv: Invoice) => inv.id === Number(id))
        if (foundInvoice) {
          setInvoice(foundInvoice)
        }
        setContracts(data.invoices)
        setLoading(false)
      })
  }, [id])

  const handleBack = () => {
    if (window.history.length > 1) {
      router.back();
    } else {
      router.push("/execution-operations/deliveryinvoicesinput");
    }
  }

  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('Invoice saved!');
      router.refresh();
    } catch (error) {
      alert('Failed to save changes.');
    }
  };

  const contractNumbers = useMemo(() => [...new Set(contracts.map(c => c["Contract number"]))], [contracts])

  if (loading) {
    return <div>Loading...</div>
  }

  if (!invoice) {
    return <div>Invoice not found</div>
  }

  return (
    <SidebarProvider
      style={{
        "--sidebar-width": "calc(var(--spacing) * 72)",
        "--header-height": "calc(var(--spacing) * 12)",
      } as React.CSSProperties}
    >
      <AppSidebar variant="inset" />
      <SidebarInset>
        <SiteHeader title="Invoice 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">Invoice Details</h2>
                <Badge variant={invoice[" Invoice saved "] === "DA" ? "default" : "destructive"}>
                  {invoice[" Invoice saved "] === "DA" ? "Saved" : "Not Saved"}
                </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">
              {/* Invoice Details Section */}
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <DollarIcon className="h-5 w-5" />
                    Invoice Details
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="mb-4">
                    <Select value={selectedContract?.["Contract number"] || ""} onValueChange={val => {
                      const contract = contracts.find(c => c["Contract number"] === val)
                      setSelectedContract(contract)
                      if (contract) {
                        setInvoice(inv => ({
                          ...inv!,
                          "Contract number": contract["Contract number"],
                          "Invoice due date": contract["Invoice due date"] || "",
                          " Invoice Total Value ": contract[" Invoice Total Value "] || "",
                          " QTTY CONTRACT ": contract[" QTTY CONTRACT "] || "",
                          "MARGIN": contract["MARGIN"] || "",
                          " QTTY UNDER MARGIN ": contract[" QTTY UNDER MARGIN "] || ""
                        }))
                      }
                    }}>
                      <SelectTrigger><SelectValue placeholder="Select contract number" /></SelectTrigger>
                      <SelectContent>
                        {contractNumbers.map(num => (
                          <SelectItem key={num} value={num}>{num}</SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div className="flex flex-col gap-2">
                      <span className="font-medium">Invoice Number</span>
                      <Input 
                        value={invoice["Invoice no"] || ""} 
                        onChange={e => setInvoice({ ...invoice, "Invoice no": e.target.value })}
                      />
                    </div>
                    <div className="flex flex-col gap-2">
                      <span className="font-medium">Invoice Date</span>
                      <Input 
                        type="date"
                        value={invoice["Invoice date"] || ""} 
                        onChange={e => setInvoice({ ...invoice, "Invoice date": e.target.value })}
                      />
                    </div>
                    <div className="flex flex-col gap-2">
                      <span className="font-medium">Invoice Quantity</span>
                      <Input 
                        type="number"
                        value={invoice[" Invoice Quantity "]?.trim() || ""} 
                        onChange={e => setInvoice({ ...invoice, " Invoice Quantity ": e.target.value })}
                      />
                    </div>
                    <div className="flex flex-col gap-2">
                      <span className="font-medium">Invoice Price</span>
                      <Input 
                        type="number"
                        value={invoice[" Invoice Price "]?.trim() || ""} 
                        onChange={e => setInvoice({ ...invoice, " Invoice Price ": e.target.value })}
                      />
                    </div>
                    <div className="flex flex-col gap-2">
                      <span className="font-medium">Invoice Currency</span>
                      <Select 
                        value={invoice[" Invoice Currency "]?.trim() || ""} 
                        onValueChange={value => setInvoice({ ...invoice, " Invoice Currency ": value })}
                      >
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="RON">RON</SelectItem>
                          <SelectItem value="EUR">EUR</SelectItem>
                          <SelectItem value="USD">USD</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                    <div className="flex flex-col gap-2">
                      <span className="font-medium">Details</span>
                      <Input 
                        value={invoice["Details"] || ""} 
                        onChange={e => setInvoice({ ...invoice, "Details": e.target.value })}
                        placeholder="Enter invoice details..."
                      />
                    </div>
                  </div>
                  <div className="flex flex-col gap-2">
                    <span className="font-medium">PDF Invoice</span>
                    <Button disabled variant="outline">Upload PDF (coming soon)</Button>
                  </div>
                </CardContent>
              </Card>

              {/* General Section */}
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <BuildingIcon className="h-5 w-5" />
                    General 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">Company</span>
                      <Input value={invoice["Company"] || ""} readOnly />
                    </div>
                    <div className="flex flex-col gap-2">
                      <span className="font-medium">Seller Company</span>
                      <Input value={invoice["Seller Company"] || ""} readOnly />
                    </div>
                    <div className="flex flex-col gap-2">
                      <span className="font-medium">Buyer Company</span>
                      <Input value={invoice["Buyer Company"] || ""} readOnly />
                    </div>
                  </div>
                </CardContent>
              </Card>

              {/* Product Information */}
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <IconPackage className="h-5 w-5" />
                    Product 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">Goods</span>
                      <Input value={invoice["Goods"] || ""} readOnly />
                    </div>
                    <div className="flex flex-col gap-2">
                      <span className="font-medium">Basis</span>
                      <Input value={invoice["Basis"] || ""} readOnly />
                    </div>
                    <div className="flex flex-col gap-2">
                      <span className="font-medium">Basis Details</span>
                      <Input value={invoice["Basis_1"] || ""} readOnly />
                    </div>
                  </div>
                </CardContent>
              </Card>

              {/* Financial Information */}
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Scale className="h-5 w-5" />
                    Financial 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">Total Value</span>
                      <Input 
                        value={invoice[" Invoice Total Value "]?.trim() ? 
                          `${invoice[" Invoice Total Value "].trim()} ${invoice[" Invoice Currency "]?.trim() || ""}` : 
                          "-"} 
                        readOnly 
                      />
                    </div>
                    <div className="flex flex-col gap-2">
                      <span className="font-medium">Open Amount</span>
                      <Input 
                        value={invoice[" Open amount "]?.trim() === "-" ? 
                          "-" : 
                          `${invoice[" Open amount "]?.trim() || ""} ${invoice[" Invoice Currency "]?.trim() || ""}`} 
                        readOnly 
                      />
                    </div>
                    <div className="flex flex-col gap-2">
                      <span className="font-medium">Delay Days</span>
                      <Input value={invoice[" Delay days "]?.trim() || "0"} readOnly />
                    </div>
                    <div className="flex flex-col gap-2">
                      <span className="font-medium">Margin</span>
                      <Input value={`${invoice["MARGIN"] || "0"}%`} readOnly />
                    </div>
                  </div>
                  <div className="flex flex-col gap-2">
                    <span className="font-medium">+margin</span>
                    <Input value={selectedContract ? (Number(selectedContract[" QTTY CONTRACT "]) * (1 + Number(selectedContract["MARGIN"])/100)).toFixed(2) : ""} readOnly />
                  </div>
                  <div className="flex flex-col gap-2">
                    <span className="font-medium">-margin</span>
                    <Input value={selectedContract ? (Number(selectedContract[" QTTY CONTRACT "]) * (1 - Number(selectedContract["MARGIN"])/100)).toFixed(2) : ""} readOnly />
                  </div>
                  <div className="flex flex-col gap-2">
                    <span className="font-medium">open qtty to -margin</span>
                    <Input value={selectedContract ? (Number(selectedContract[" QTTY CONTRACT "]) - (Number(selectedContract[" QTTY CONTRACT "]) * (1 - Number(selectedContract["MARGIN"])/100))).toFixed(2) : ""} readOnly />
                  </div>
                </CardContent>
              </Card>
            </div>
          </div>
        </div>
      </SidebarInset>
    </SidebarProvider>
  )
} 