"use client"

import { useEffect, useState } from "react"
import { useTranslation } from "react-i18next"
import { useRouter } from "next/navigation"
import { AppSidebar } from "@/components/app-sidebar"
import { SiteHeader } from "@/components/site-header"
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Textarea } from "@/components/ui/textarea"
import { FileIcon, LinkIcon, UserIcon, BuildingIcon, CalendarIcon, DollarIcon } from "@/components/ui/icons"
import { Truck, Scale } from "lucide-react"

interface Contract {
  id: number;
  contractNumber: string;
  contractDate: string;
  brokerageCompany: string;
  status: string;
  contractType: string;
  basicInfo: {
    sellerCompany: string;
    buyerCompany: string;
    goodsCode: string;
    goods: string;
    cropYear: string;
    origin: string;
    goodsFullDescription: string;
    goodsFullDescriptionENG: string;
  };
  productInfo: {
    qualityTerms: string;
    qualityTermsENG: string;
    quantity: number;
    quantityTolerance: string;
    quantityToleranceENG: string;
    executedQuantity: number;
    remainingToBeExecuted: number;
  };
  financialInfo: {
    pricePerMt: number;
    priceCurrency: string;
    priceCurrencyDetails: string;
    paymentDays: number;
    paymentTerms: string;
    paymentTermsENG: string;
  };
  transportInfo: {
    incoterms: string;
    deliveryPlace: string;
    deliveryPlaceENG: string;
    deliveryDateFrom: string;
    deliveryDateTo: string;
    deliveryTerm: string;
    deliveryTermENG: string;
  };
  documents: {
    contractDraft: string;
    sellerSigned: string;
    buyerSigned: string;
    brokerSigned: string;
    contractSignedStatus: string;
    contractDateCheck: string;
    externalContractNo?: string;
  };
  brokerInfo: {
    whoIsPayingCommission: string;
    sellerCommission: number;
    sellerCommissionCurrency: string;
    buyerCommission: string;
    buyerCommissionCurrency: string;
    sellerBrokerCode: string;
    buyerBrokerCode: string;
    totalCommissionEURmt: number;
    totalValueCommissionEUR: number;
    sellerBrokerCommission: number;
    buyerBrokerCommission: number;
  };
  otherInfo: {
    otherTerms: string;
    otherTermsENG: string;
    pic: string;
    executionYear: string;
    contractCurrencyDate: string;
    sellerExchangeRate: number;
    buyerExchangeRate: string;
  };
}

export default function ContractEditPage({ params }: { params: { id: string } }) {
  const [contract, setContract] = useState<Contract | null>(null)
  const { t } = useTranslation()
  const router = useRouter()

  useEffect(() => {
    fetch(`/contracts/api/contractsdata`)
      .then(res => res.json())
      .then(data => {
        const foundContract = data.find((c: Contract) => c.id === parseInt(params.id))
        setContract(foundContract)
      })
  }, [params.id])

  if (!contract) {
    return <div>Loading...</div>
  }

  const handleChange = (section: keyof Contract, field: string, value: any) => {
    setContract(prev => {
      if (!prev) return null;
      if (section === 'basicInfo' || section === 'productInfo' || section === 'financialInfo' || 
          section === 'transportInfo' || section === 'documents' || section === 'brokerInfo' || 
          section === 'otherInfo') {
        return {
          ...prev,
          [section]: {
            ...prev[section],
            [field]: value
          }
        };
      }
      return {
        ...prev,
        [field]: value
      };
    });
  };

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault()
    try {
      const response = await fetch(`/contracts/api/contractsdata`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(contract),
      })
      if (response.ok) {
        router.push(`/contracts/${contract.id}`)
      }
    } catch (error) {
      console.error('Error updating contract:', error)
    }
  }

  return (
    <SidebarProvider
      style={{
        "--sidebar-width": "calc(var(--spacing) * 72)",
        "--header-height": "calc(var(--spacing) * 12)",
      } as React.CSSProperties}
    >
      <AppSidebar variant="inset" />
      <SidebarInset>
        <SiteHeader />
        <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="flex justify-between items-center px-4 lg:px-6">
                <h2 className="text-2xl font-bold">{t("contractdetail.edit")}</h2>
                <div className="flex gap-2">
                  <Button type="submit" form="contract-form">
                    {t("contractdetail.save")}
                  </Button>
                  <Button variant="outline" onClick={() => router.back()}>
                    {t("contractdetail.back")}
                  </Button>
                </div>
              </div>

              <form id="contract-form" onSubmit={handleSubmit} className="px-4 lg:px-6">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <Card>
                    <CardHeader>
                      <CardTitle className="flex items-center gap-2">
                        <BuildingIcon className="h-5 w-5" />
                        {t("contractdetail.basicinfo")}
                      </CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-4">
                      <div className="grid grid-cols-2 gap-4">
                        <div>
                          <Label>{t("contractdetail.sellercompany")}</Label>
                          <Input
                            value={contract.basicInfo.sellerCompany}
                            onChange={(e) => handleChange('basicInfo', 'sellerCompany', e.target.value)}
                          />
                        </div>
                        <div>
                          <Label>{t("contractdetail.buyercompany")}</Label>
                          <Input
                            value={contract.basicInfo.buyerCompany}
                            onChange={(e) => handleChange('basicInfo', 'buyerCompany', e.target.value)}
                          />
                        </div>
                        <div>
                          <Label>{t("contractdetail.goods")}</Label>
                          <Input
                            value={contract.basicInfo.goods}
                            onChange={(e) => handleChange('basicInfo', 'goods', e.target.value)}
                          />
                        </div>
                        <div>
                          <Label>{t("contractdetail.goodscode")}</Label>
                          <Input
                            value={contract.basicInfo.goodsCode}
                            onChange={(e) => handleChange('basicInfo', 'goodsCode', e.target.value)}
                          />
                        </div>
                        <div>
                          <Label>{t("contractdetail.cropyear")}</Label>
                          <Input
                            value={contract.basicInfo.cropYear}
                            onChange={(e) => handleChange('basicInfo', 'cropYear', e.target.value)}
                          />
                        </div>
                        <div>
                          <Label>{t("contractdetail.origin")}</Label>
                          <Input
                            value={contract.basicInfo.origin}
                            onChange={(e) => handleChange('basicInfo', 'origin', e.target.value)}
                          />
                        </div>
                        <div className="col-span-2">
                          <Label>{t("contractdetail.goodsfulldescription")}</Label>
                          <Textarea
                            value={contract.basicInfo.goodsFullDescription}
                            onChange={(e) => handleChange('basicInfo', 'goodsFullDescription', e.target.value)}
                          />
                        </div>
                        <div className="col-span-2">
                          <Label>{t("contractdetail.goodsfulldescriptioneng")}</Label>
                          <Textarea
                            value={contract.basicInfo.goodsFullDescriptionENG}
                            onChange={(e) => handleChange('basicInfo', 'goodsFullDescriptionENG', e.target.value)}
                          />
                        </div>
                      </div>
                    </CardContent>
                  </Card>

                  <Card>
                    <CardHeader>
                      <CardTitle className="flex items-center gap-2">
                        <Scale className="h-5 w-5" />
                        {t("contractdetail.productinfo")}
                      </CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-4">
                      <div className="grid grid-cols-2 gap-4">
                        <div>
                          <Label>{t("contractdetail.quantity")}</Label>
                          <Input
                            type="number"
                            value={contract.productInfo.quantity}
                            onChange={(e) => handleChange('productInfo', 'quantity', parseFloat(e.target.value))}
                          />
                        </div>
                        <div>
                          <Label>{t("contractdetail.quantitytolerance")}</Label>
                          <Input
                            value={contract.productInfo.quantityTolerance}
                            onChange={(e) => handleChange('productInfo', 'quantityTolerance', e.target.value)}
                          />
                        </div>
                        <div>
                          <Label>{t("contractdetail.executedquantity")}</Label>
                          <Input
                            type="number"
                            value={contract.productInfo.executedQuantity}
                            onChange={(e) => handleChange('productInfo', 'executedQuantity', parseFloat(e.target.value))}
                          />
                        </div>
                        <div>
                          <Label>{t("contractdetail.remainingtobeexecuted")}</Label>
                          <Input
                            type="number"
                            value={contract.productInfo.remainingToBeExecuted}
                            onChange={(e) => handleChange('productInfo', 'remainingToBeExecuted', parseFloat(e.target.value))}
                          />
                        </div>
                        <div className="col-span-2">
                          <Label>{t("contractdetail.qualityterms")}</Label>
                          <Textarea
                            value={contract.productInfo.qualityTerms}
                            onChange={(e) => handleChange('productInfo', 'qualityTerms', e.target.value)}
                          />
                        </div>
                        <div className="col-span-2">
                          <Label>{t("contractdetail.qualitytermseng")}</Label>
                          <Textarea
                            value={contract.productInfo.qualityTermsENG}
                            onChange={(e) => handleChange('productInfo', 'qualityTermsENG', e.target.value)}
                          />
                        </div>
                      </div>
                    </CardContent>
                  </Card>

                  <Card>
                    <CardHeader>
                      <CardTitle className="flex items-center gap-2">
                        <DollarIcon className="h-5 w-5" />
                        {t("contractdetail.financialinfo")}
                      </CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-4">
                      <div className="grid grid-cols-2 gap-4">
                        <div>
                          <Label>{t("contractdetail.pricepermt")}</Label>
                          <Input
                            type="number"
                            value={contract.financialInfo.pricePerMt}
                            onChange={(e) => handleChange('financialInfo', 'pricePerMt', parseFloat(e.target.value))}
                          />
                        </div>
                        <div>
                          <Label>{t("contractdetail.paymentdays")}</Label>
                          <Input
                            type="number"
                            value={contract.financialInfo.paymentDays}
                            onChange={(e) => handleChange('financialInfo', 'paymentDays', parseInt(e.target.value))}
                          />
                        </div>
                        <div className="col-span-2">
                          <Label>{t("contractdetail.pricecurrencydetails")}</Label>
                          <Textarea
                            value={contract.financialInfo.priceCurrencyDetails}
                            onChange={(e) => handleChange('financialInfo', 'priceCurrencyDetails', e.target.value)}
                          />
                        </div>
                        <div className="col-span-2">
                          <Label>{t("contractdetail.paymentterms")}</Label>
                          <Textarea
                            value={contract.financialInfo.paymentTerms}
                            onChange={(e) => handleChange('financialInfo', 'paymentTerms', e.target.value)}
                          />
                        </div>
                        <div className="col-span-2">
                          <Label>{t("contractdetail.paymenttermseng")}</Label>
                          <Textarea
                            value={contract.financialInfo.paymentTermsENG}
                            onChange={(e) => handleChange('financialInfo', 'paymentTermsENG', e.target.value)}
                          />
                        </div>
                      </div>
                    </CardContent>
                  </Card>

                  <Card>
                    <CardHeader>
                      <CardTitle className="flex items-center gap-2">
                        <Truck className="h-5 w-5" />
                        {t("contractdetail.transportinfo")}
                      </CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-4">
                      <div className="grid grid-cols-2 gap-4">
                        <div>
                          <Label>{t("contractdetail.incoterms")}</Label>
                          <Input
                            value={contract.transportInfo.incoterms}
                            onChange={(e) => handleChange('transportInfo', 'incoterms', e.target.value)}
                          />
                        </div>
                        <div>
                          <Label>{t("contractdetail.deliveryplace")}</Label>
                          <Input
                            value={contract.transportInfo.deliveryPlace}
                            onChange={(e) => handleChange('transportInfo', 'deliveryPlace', e.target.value)}
                          />
                        </div>
                        <div>
                          <Label>{t("contractdetail.deliverydatefrom")}</Label>
                          <Input
                            type="date"
                            value={contract.transportInfo.deliveryDateFrom}
                            onChange={(e) => handleChange('transportInfo', 'deliveryDateFrom', e.target.value)}
                          />
                        </div>
                        <div>
                          <Label>{t("contractdetail.deliverydateto")}</Label>
                          <Input
                            type="date"
                            value={contract.transportInfo.deliveryDateTo}
                            onChange={(e) => handleChange('transportInfo', 'deliveryDateTo', e.target.value)}
                          />
                        </div>
                        <div className="col-span-2">
                          <Label>{t("contractdetail.deliveryterm")}</Label>
                          <Input
                            value={contract.transportInfo.deliveryTerm}
                            onChange={(e) => handleChange('transportInfo', 'deliveryTerm', e.target.value)}
                          />
                        </div>
                        <div className="col-span-2">
                          <Label>{t("contractdetail.deliverytermeng")}</Label>
                          <Input
                            value={contract.transportInfo.deliveryTermENG}
                            onChange={(e) => handleChange('transportInfo', 'deliveryTermENG', e.target.value)}
                          />
                        </div>
                      </div>
                    </CardContent>
                  </Card>

                  <Card>
                    <CardHeader>
                      <CardTitle className="flex items-center gap-2">
                        <FileIcon className="h-5 w-5" />
                        {t("contractdetail.documents")}
                      </CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-4">
                      <div className="grid grid-cols-2 gap-4">
                        <div>
                          <Label>{t("contractdetail.contractdraft")}</Label>
                          <Input
                            value={contract.documents.contractDraft}
                            onChange={(e) => handleChange('documents', 'contractDraft', e.target.value)}
                          />
                        </div>
                        <div>
                          <Label>{t("contractdetail.contractsignedstatus")}</Label>
                          <Input
                            value={contract.documents.contractSignedStatus}
                            onChange={(e) => handleChange('documents', 'contractSignedStatus', e.target.value)}
                          />
                        </div>
                        <div>
                          <Label>{t("contractdetail.sellersigned")}</Label>
                          <Input
                            value={contract.documents.sellerSigned}
                            onChange={(e) => handleChange('documents', 'sellerSigned', e.target.value)}
                          />
                        </div>
                        <div>
                          <Label>{t("contractdetail.buyersigned")}</Label>
                          <Input
                            value={contract.documents.buyerSigned}
                            onChange={(e) => handleChange('documents', 'buyerSigned', e.target.value)}
                          />
                        </div>
                        <div>
                          <Label>{t("contractdetail.brokersigned")}</Label>
                          <Input
                            value={contract.documents.brokerSigned}
                            onChange={(e) => handleChange('documents', 'brokerSigned', e.target.value)}
                          />
                        </div>
                        <div>
                          <Label>{t("contractdetail.contractdatecheck")}</Label>
                          <Input
                            value={contract.documents.contractDateCheck}
                            onChange={(e) => handleChange('documents', 'contractDateCheck', e.target.value)}
                          />
                        </div>
                        {contract.documents.externalContractNo && (
                          <div className="col-span-2">
                            <Label>{t("contractdetail.externalcontractno")}</Label>
                            <Input
                              value={contract.documents.externalContractNo}
                              onChange={(e) => handleChange('documents', 'externalContractNo', e.target.value)}
                            />
                          </div>
                        )}
                      </div>
                    </CardContent>
                  </Card>

                  <Card>
                    <CardHeader>
                      <CardTitle className="flex items-center gap-2">
                        <UserIcon className="h-5 w-5" />
                        {t("contractdetail.brokerinfo")}
                      </CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-4">
                      <div className="grid grid-cols-2 gap-4">
                        <div>
                          <Label>{t("contractdetail.whoispayingcommission")}</Label>
                          <Input
                            value={contract.brokerInfo.whoIsPayingCommission}
                            onChange={(e) => handleChange('brokerInfo', 'whoIsPayingCommission', e.target.value)}
                          />
                        </div>
                        <div>
                          <Label>{t("contractdetail.sellercommission")}</Label>
                          <Input
                            type="number"
                            value={contract.brokerInfo.sellerCommission}
                            onChange={(e) => handleChange('brokerInfo', 'sellerCommission', parseFloat(e.target.value))}
                          />
                        </div>
                        <div>
                          <Label>{t("contractdetail.buyercommission")}</Label>
                          <Input
                            value={contract.brokerInfo.buyerCommission}
                            onChange={(e) => handleChange('brokerInfo', 'buyerCommission', e.target.value)}
                          />
                        </div>
                        <div>
                          <Label>{t("contractdetail.totalcommissioneurmt")}</Label>
                          <Input
                            type="number"
                            value={contract.brokerInfo.totalCommissionEURmt}
                            onChange={(e) => handleChange('brokerInfo', 'totalCommissionEURmt', parseFloat(e.target.value))}
                          />
                        </div>
                        <div>
                          <Label>{t("contractdetail.totalvaluecommissioneur")}</Label>
                          <Input
                            type="number"
                            value={contract.brokerInfo.totalValueCommissionEUR}
                            onChange={(e) => handleChange('brokerInfo', 'totalValueCommissionEUR', parseFloat(e.target.value))}
                          />
                        </div>
                        <div>
                          <Label>{t("contractdetail.sellerbrokercommission")}</Label>
                          <Input
                            type="number"
                            value={contract.brokerInfo.sellerBrokerCommission}
                            onChange={(e) => handleChange('brokerInfo', 'sellerBrokerCommission', parseFloat(e.target.value))}
                          />
                        </div>
                        <div>
                          <Label>{t("contractdetail.buyerbrokercommission")}</Label>
                          <Input
                            type="number"
                            value={contract.brokerInfo.buyerBrokerCommission}
                            onChange={(e) => handleChange('brokerInfo', 'buyerBrokerCommission', parseFloat(e.target.value))}
                          />
                        </div>
                      </div>
                    </CardContent>
                  </Card>

                  <Card>
                    <CardHeader>
                      <CardTitle className="flex items-center gap-2">
                        <FileIcon className="h-5 w-5" />
                        {t("contractdetail.otherinfo")}
                      </CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-4">
                      <div className="grid grid-cols-2 gap-4">
                        <div>
                          <Label>{t("contractdetail.pic")}</Label>
                          <Input
                            value={contract.otherInfo.pic}
                            onChange={(e) => handleChange('otherInfo', 'pic', e.target.value)}
                          />
                        </div>
                        <div>
                          <Label>{t("contractdetail.executionyear")}</Label>
                          <Input
                            value={contract.otherInfo.executionYear}
                            onChange={(e) => handleChange('otherInfo', 'executionYear', e.target.value)}
                          />
                        </div>
                        <div>
                          <Label>{t("contractdetail.contractcurrencydate")}</Label>
                          <Input
                            value={contract.otherInfo.contractCurrencyDate}
                            onChange={(e) => handleChange('otherInfo', 'contractCurrencyDate', e.target.value)}
                          />
                        </div>
                        <div>
                          <Label>{t("contractdetail.sellerexchangerate")}</Label>
                          <Input
                            type="number"
                            value={contract.otherInfo.sellerExchangeRate}
                            onChange={(e) => handleChange('otherInfo', 'sellerExchangeRate', parseFloat(e.target.value))}
                          />
                        </div>
                        <div>
                          <Label>{t("contractdetail.buyerexchangerate")}</Label>
                          <Input
                            value={contract.otherInfo.buyerExchangeRate}
                            onChange={(e) => handleChange('otherInfo', 'buyerExchangeRate', e.target.value)}
                          />
                        </div>
                        <div className="col-span-2">
                          <Label>{t("contractdetail.otherterms")}</Label>
                          <Textarea
                            value={contract.otherInfo.otherTerms}
                            onChange={(e) => handleChange('otherInfo', 'otherTerms', e.target.value)}
                          />
                        </div>
                        <div className="col-span-2">
                          <Label>{t("contractdetail.othertermseng")}</Label>
                          <Textarea
                            value={contract.otherInfo.otherTermsENG}
                            onChange={(e) => handleChange('otherInfo', 'otherTermsENG', e.target.value)}
                          />
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                </div>
              </form>
            </div>
          </div>
        </div>
      </SidebarInset>
    </SidebarProvider>
  )
} 