"use client"

import { AppSidebar } from "@/components/app-sidebar"
import { SiteHeader } from "@/components/site-header"
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar"
import { useEffect, useState } from "react"
import { useTranslation } from "react-i18next"
import { useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import { Checkbox } from "@/components/ui/checkbox"
import { format } from "date-fns"

type Contract = {
  id: number
  number: string
  supplier: {
    name: string
    details: string
    vat: string
    address: string
  }
  buyer: {
    name: string
    details: string
    vat: string
    address: string
  }
  product: string
  price: number
  priceRON: number
  currency: string
  deliveryTerms: string
  vatRate: number
  vatType: string
  paymentTerms: string
  exchangeRate: number
  qualityParams: {
    name: string
    value: string
  }[]
  costs: {
    name: string
    value: number
    currency: string
  }[]
}

type Receipt = {
  id: number
  number: string
  date: string
  quantity: number
  quality: {
    name: string
    value: string
  }[]
  invoiceNumber: string | null
}

type PriceCalculation = {
  id?: number
  type: "price" | "cd" | "matif"
  date: string
  contract: Contract
  receipts: Receipt[]
  penalties: {
    name: string
    value: number
    currency: string
  }[]
  totalValue: number
  totalValueRON: number
  vatAmount: number
  vatAmountRON: number
  currency: string
}

export default function NewPriceCalculationPage() {
  const router = useRouter()
  const { t } = useTranslation()
  const [contracts, setContracts] = useState<any[]>([])
  const [selectedContract, setSelectedContract] = useState<any | null>(null)
  const [receipts, setReceipts] = useState<Receipt[]>([])
  const [selectedReceipts, setSelectedReceipts] = useState<number[]>([])
  const [calculationType, setCalculationType] = useState<"price" | "cd" | "matif">("price")
  const [calculationDate, setCalculationDate] = useState(format(new Date(), "yyyy-MM-dd"))
  const [showQualityDialog, setShowQualityDialog] = useState(false)
  const [showCostsDialog, setShowCostsDialog] = useState(false)

  useEffect(() => {
    fetch("/contracts/contractsdata.json")
      .then(res => res.json())
      .then(data => setContracts(data))
      .catch(err => console.error("Error loading contracts:", err))
  }, [])

  useEffect(() => {
    if (selectedContract) {
      // Fetch available receipts for the selected contract
      fetch(`/api/contracts/${selectedContract.id}/receipts`)
        .then(res => res.json())
        .then(data => {
          // Filter receipts that don't have an invoice
          const availableReceipts = data.filter((r: Receipt) => !r.invoiceNumber)
          setReceipts(availableReceipts)
        })
        .catch(error => console.error("Error fetching receipts:", error))
    }
  }, [selectedContract])

  const handleContractSelect = (contractId: string) => {
    const contract = contracts.find(c => c.id === parseInt(contractId))
    setSelectedContract(contract || null)
  }

  const handleReceiptToggle = (receiptId: number) => {
    setSelectedReceipts(prev => 
      prev.includes(receiptId)
        ? prev.filter(id => id !== receiptId)
        : [...prev, receiptId]
    )
  }

  const handleSave = async (action: "save" | "pdf" | "email") => {
    if (!selectedContract || selectedReceipts.length === 0) return

    const calculation: PriceCalculation = {
      type: calculationType,
      date: calculationDate,
      contract: selectedContract,
      receipts: receipts.filter(r => selectedReceipts.includes(r.id)),
      penalties: [], // Will be calculated by the API
      totalValue: 0, // Will be calculated by the API
      totalValueRON: 0,
      vatAmount: 0,
      vatAmountRON: 0,
      currency: selectedContract.currency
    }

    try {
      const response = await fetch("/api/price-calculations", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(calculation)
      })

      if (!response.ok) throw new Error("Failed to save calculation")

      const savedCalculation = await response.json()

      // Show calculation results
      const resultMessage = `
        Total Value: ${savedCalculation.totalValue} ${savedCalculation.currency}
        Total Value (RON): ${savedCalculation.totalValueRON} RON
        VAT Amount: ${savedCalculation.vatAmount} ${savedCalculation.currency}
        VAT Amount (RON): ${savedCalculation.vatAmountRON} RON
        Penalties: ${savedCalculation.penalties.map((p: any) => 
          `${p.name}: ${p.value} ${p.currency}`
        ).join(", ")}
      `

      if (action === "pdf") {
        // Generate PDF
        window.open(`/api/price-calculations/${savedCalculation.id}/pdf`, "_blank")
      } else if (action === "email") {
        // Send email with PDF
        await fetch(`/api/price-calculations/${savedCalculation.id}/email`, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ emailTemplate: resultMessage })
        })
      }

      // Show success message
      alert(resultMessage)
      router.push("/execution-operations/pricecalculation")
    } catch (error) {
      console.error("Error saving calculation:", error)
      alert("Failed to save calculation")
    }
  }

  return (
    <SidebarProvider
      style={{
        "--sidebar-width": "calc(var(--spacing) * 72)",
        "--header-height": "calc(var(--spacing) * 12)",
      } as React.CSSProperties}
    >
      <AppSidebar variant="inset" />
      <SidebarInset>
        <SiteHeader title={t("priceCalculation.new")} />
        <div className="flex flex-1 flex-col">
          <div className="@container/main flex flex-1 flex-col gap-2">
            <div className="flex flex-col gap-4 py-4 md:gap-6 md:py-6">
              <div className="px-4 lg:px-6">
                <Card>
                  <CardHeader>
                    <CardTitle>{t("priceCalculation.basicInfo")}</CardTitle>
                    <CardDescription>{t("priceCalculation.basicInfoDescription")}</CardDescription>
                  </CardHeader>
                  <CardContent className="grid gap-4">
                    <div className="grid gap-2">
                      <Label>{t("priceCalculation.contract")}</Label>
                      <Select onValueChange={handleContractSelect}>
                        <SelectTrigger>
                          <SelectValue placeholder={t("priceCalculation.selectContract")} />
                        </SelectTrigger>
                        <SelectContent>
                          {Array.isArray(contracts) && contracts.map(contract => (
                            <SelectItem key={contract.id} value={contract.id.toString()}>
                              {contract.contractNumber} ({contract.contractDate})
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>

                    {selectedContract && (
                      <div className="grid gap-4">
                        <Card>
                          <CardHeader>
                            <CardTitle>Contract Preview</CardTitle>
                          </CardHeader>
                          <CardContent>
                            <div className="grid grid-cols-2 gap-4">
                              <div>
                                <Label>Contract Number</Label>
                                <div className="text-sm">{selectedContract.contractNumber}</div>
                                <Label>Date</Label>
                                <div className="text-sm">{selectedContract.contractDate}</div>
                              </div>
                              <div>
                                <Label>Product</Label>
                                <div className="text-sm">{selectedContract.basicInfo?.goodsFullDescription || selectedContract.basicInfo?.goods}</div>
                              </div>
                            </div>
                            <div className="grid grid-cols-2 gap-4 mt-2">
                              <div>
                                <Label>Seller</Label>
                                <div className="text-sm font-bold">{selectedContract.basicInfo?.sellerCompany}</div>
                                <div className="text-sm">VAT: {selectedContract.general?.sellerVat || '-'}</div>
                                <div className="text-sm">Address: {selectedContract.sellerAddress || '-'}</div>
                                <div className="text-sm">Bank: {selectedContract.sellerBank || '-'}</div>
                              </div>
                              <div>
                                <Label>Buyer</Label>
                                <div className="text-sm font-bold">{selectedContract.basicInfo?.buyerCompany}</div>
                                <div className="text-sm">VAT: {selectedContract.general?.buyerVat || '-'}</div>
                                <div className="text-sm">Address: {selectedContract.buyerAddress || '-'}</div>
                                <div className="text-sm">Bank: {selectedContract.buyerBank || '-'}</div>
                              </div>
                            </div>
                            <div className="grid grid-cols-2 gap-4 mt-2">
                              <div>
                                <Label>Contract Price</Label>
                                <div className="text-sm">{selectedContract.financialInfo?.pricePerMt} {selectedContract.financialInfo?.priceCurrency}</div>
                              </div>
                              <div>
                                <Label>Transport</Label>
                                <div className="text-sm">{selectedContract.transportInfo?.deliveryPlace}</div>
                              </div>
                            </div>
                          </CardContent>
                        </Card>
                      </div>
                    )}

                    <div className="grid gap-2">
                      <Label>{t("priceCalculation.type")}</Label>
                      <Select value={calculationType} onValueChange={(value: "price" | "cd" | "matif") => setCalculationType(value)}>
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="price">{t("priceCalculation.types.price")}</SelectItem>
                          <SelectItem value="cd">{t("priceCalculation.types.cd")}</SelectItem>
                          <SelectItem value="matif">{t("priceCalculation.types.matif")}</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>

                    <div className="grid gap-2">
                      <Label>{t("priceCalculation.date")}</Label>
                      <Input
                        type="date"
                        value={calculationDate}
                        onChange={(e) => setCalculationDate(e.target.value)}
                      />
                    </div>

                    {selectedContract && (
                      <div className="flex gap-2">
                        <Dialog open={showQualityDialog} onOpenChange={setShowQualityDialog}>
                          <DialogTrigger asChild>
                            <Button variant="outline">
                              {t("priceCalculation.viewQualityParams")}
                            </Button>
                          </DialogTrigger>
                          <DialogContent>
                            <DialogHeader>
                              <DialogTitle>{t("priceCalculation.qualityParams")}</DialogTitle>
                              <DialogDescription>
                                {t("priceCalculation.qualityParamsDescription")}
                              </DialogDescription>
                            </DialogHeader>
                            <Table>
                              <TableHeader>
                                <TableRow>
                                  <TableHead>{t("priceCalculation.parameter")}</TableHead>
                                  <TableHead>{t("priceCalculation.value")}</TableHead>
                                </TableRow>
                              </TableHeader>
                              <TableBody>
                                {Array.isArray(selectedContract?.qualityParams) && selectedContract.qualityParams.map((param: any, index: number) => (
                                  <TableRow key={index}>
                                    <TableCell>{param.name}</TableCell>
                                    <TableCell>{param.value}</TableCell>
                                  </TableRow>
                                ))}
                              </TableBody>
                            </Table>
                          </DialogContent>
                        </Dialog>

                        <Dialog open={showCostsDialog} onOpenChange={setShowCostsDialog}>
                          <DialogTrigger asChild>
                            <Button variant="outline">
                              {t("priceCalculation.viewCosts")}
                            </Button>
                          </DialogTrigger>
                          <DialogContent>
                            <DialogHeader>
                              <DialogTitle>{t("priceCalculation.costs")}</DialogTitle>
                              <DialogDescription>
                                {t("priceCalculation.costsDescription")}
                              </DialogDescription>
                            </DialogHeader>
                            <Table>
                              <TableHeader>
                                <TableRow>
                                  <TableHead>{t("priceCalculation.costName")}</TableHead>
                                  <TableHead>{t("priceCalculation.value")}</TableHead>
                                  <TableHead>{t("priceCalculation.currency")}</TableHead>
                                </TableRow>
                              </TableHeader>
                              <TableBody>
                                {Array.isArray(selectedContract?.costs) && selectedContract.costs.map((cost: any, index: number) => (
                                  <TableRow key={index}>
                                    <TableCell>{cost.name}</TableCell>
                                    <TableCell>{cost.value}</TableCell>
                                    <TableCell>{cost.currency}</TableCell>
                                  </TableRow>
                                ))}
                              </TableBody>
                            </Table>
                          </DialogContent>
                        </Dialog>
                      </div>
                    )}
                  </CardContent>
                </Card>

                {selectedContract && (
                  <Card className="mt-4">
                    <CardHeader>
                      <CardTitle>{t("priceCalculation.receipts")}</CardTitle>
                      <CardDescription>{t("priceCalculation.receiptsDescription")}</CardDescription>
                    </CardHeader>
                    <CardContent>
                      <Table>
                        <TableHeader>
                          <TableRow>
                            <TableHead>{t("priceCalculation.select")}</TableHead>
                            <TableHead>{t("priceCalculation.receiptNumber")}</TableHead>
                            <TableHead>{t("priceCalculation.date")}</TableHead>
                            <TableHead>{t("priceCalculation.quantity")}</TableHead>
                            <TableHead>{t("priceCalculation.quality")}</TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {Array.isArray(receipts) && receipts.map(receipt => (
                            <TableRow key={receipt.id}>
                              <TableCell>
                                <Checkbox
                                  checked={selectedReceipts.includes(receipt.id)}
                                  onCheckedChange={() => handleReceiptToggle(receipt.id)}
                                />
                              </TableCell>
                              <TableCell>{receipt.number}</TableCell>
                              <TableCell>{format(new Date(receipt.date), "dd/MM/yyyy")}</TableCell>
                              <TableCell>{receipt.quantity}</TableCell>
                              <TableCell>
                                {Array.isArray(receipt.quality) && receipt.quality.map((q, i) => (
                                  <div key={i} className="text-sm">
                                    {q.name}: {q.value}
                                  </div>
                                ))}
                              </TableCell>
                            </TableRow>
                          ))}
                        </TableBody>
                      </Table>
                    </CardContent>
                  </Card>
                )}

                <div className="flex justify-end gap-4 mt-4">
                  <Button variant="outline" onClick={() => router.back()}>
                    {t("common.cancel")}
                  </Button>
                  <Button onClick={() => handleSave("save")}>
                    {t("common.save")}
                  </Button>
                  <Button onClick={() => handleSave("pdf")}>
                    {t("priceCalculation.saveAndGeneratePDF")}
                  </Button>
                  <Button onClick={() => handleSave("email")}>
                    {t("priceCalculation.saveAndSendEmail")}
                  </Button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </SidebarInset>
    </SidebarProvider>
  )
} 