"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, 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"
import { Combobox } from "@/components/combobox"
import { ComboboxFull } from "@/components/combobox-full"
import { Calendar } from "@/components/ui/calendar"
import { format } from "date-fns"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { cn } from "@/lib/utils"
import { CalendarIcon } from "lucide-react"
import {
  Tabs,
  TabsContent,
  TabsList,
  TabsTrigger,
} from "@/components/ui/tabs"
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger, DialogDescription, DialogFooter } from "@/components/ui/dialog"
import { Label } from "@/components/ui/label"

// Helper to get next ID from existing contracts
async function getNextId(): Promise<number> {
  try {
    const response = await fetch('/contracts/api/contractsdata');
    if (!response.ok) throw new Error('Failed to fetch contracts');
    const contracts = await response.json();
    const maxId = Math.max(...contracts.map((c: any) => c.id || 0), 0);
    return maxId + 1;
  } catch (error) {
    console.error('Error getting next ID:', error);
    return 1; // Default to 1 if there's an error
  }
}

// Helper to map contract state to full contractsdata.json structure
function mapToFullContract(
  contract: any,
  selectedCompany: string,
  selectedBuyerCompany: string,
  companyNotes: Record<string, { buyerNote: string; sellerNote: string }>
) {
  // Helper function to format date to MM/DD/YY
  const formatDate = (dateString: string | undefined) => {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.toLocaleDateString('en-US', {
      month: 'numeric',
      day: 'numeric',
      year: '2-digit'
    });
  };

  // Ensure delivery dates are properly set
  const deliveryStart = contract.productInfo?.deliveryStart || contract.delivery?.deliveryStart;
  const deliveryEnd = contract.productInfo?.deliveryEnd || contract.delivery?.deliveryEnd;

  return {
    id: contract.id || '',
    contractNumber: contract.contractNumber || '',
    contractDate: formatDate(contract.contractDate) || formatDate(new Date().toISOString()),
    brokerageCompany: contract.brokerageCompany || '',
    status: contract.status || '',
    contractType: contract.contractType || '',
    initialQuantity: contract.productInfo?.quantity || '',
    executedQuantity: contract.executedQuantity || '',
    remainingToBeExecuted: contract.remainingToBeExecuted || '',
    commissionInvoice: contract.commissionInvoice || '',
    totalCommisionEUR_mt: contract.totalCommisionEUR_mt || '',
    totalValueCommissionEUR: contract.totalValueCommissionEUR || '',
    sellerBrokerCommission: contract.general?.sellerBrokerCommission || '',
    buyerBrokerCommission: contract.general?.buyerBrokerCommission || '',
    contractCurrencyDate: formatDate(contract.contractCurrencyDate) || formatDate(new Date().toISOString()),
    guaranteesBO: contract.guaranteesBO || '',
    statusBO: contract.statusBO || '',
    basicInfo: {
      sellerCompany: selectedCompany || '',
      buyerCompany: selectedBuyerCompany || '',
      goodsCode: contract.productInfo?.code || '',
      goods: contract.productInfo?.name || '',
      cropYear: contract.productInfo?.cropYear || '',
      origin: contract.productInfo?.origin || '',
      goodsFullDescription: contract.productInfo?.goodsFullDescription || '',
      buyerNote: companyNotes[selectedBuyerCompany]?.buyerNote || '',
      sellerNote: companyNotes[selectedCompany]?.sellerNote || '',
      buyerEmail: contract.basicInfo?.buyerEmail || '',
      sellerEmail: contract.basicInfo?.sellerEmail || ''
    },
    productInfo: {
      qualityTerms: contract.productInfo?.qualityTerms || '',
      quantity: contract.productInfo?.quantity || '',
      quantityTolerance: contract.productInfo?.quantityTolerance || '',
      quality: contract.productInfo?.quality || '',
      qualityOption: contract.productInfo?.qualityOption || '',
      qualityFinalAt: contract.productInfo?.qualityFinalAt || '',
      unit: contract.productInfo?.unit || '',
      toleranceType: contract.productInfo?.toleranceType || '',
      tolerance: contract.productInfo?.tolerance || '',
      quantityOption: contract.productInfo?.quantityOption || '',
      finalAt: contract.productInfo?.finalAt || '',
      deliveryStart: formatDate(deliveryStart) || '',
      deliveryEnd: formatDate(deliveryEnd) || '',
      deliveryOption: contract.productInfo?.deliveryOption || '',
      deliveryExtension: contract.productInfo?.deliveryExtension || '',
      guarantees: contract.productInfo?.guarantees || '',
      guaranteeType: contract.productInfo?.guaranteeType || '',
      guaranteeTitle: contract.productInfo?.guaranteeTitle || '',
      guaranteeStatus: contract.productInfo?.guaranteeStatus || ''
    },
    financialInfo: {
      pricePerMt: contract.financialInfo?.pricePerMt || '',
      priceCurrency: contract.financialInfo?.priceCurrency || '',
      paymentDays: contract.financialInfo?.paymentDays || '',
      paymentTerms: contract.financialInfo?.paymentTerms || '',
      priceType: contract.financialInfo?.priceType || '',
      spread1: contract.financialInfo?.spread1 || '',
      spread2: contract.financialInfo?.spread2 || '',
      matifExchange: contract.financialInfo?.matifExchange || '',
      matifPrice: contract.financialInfo?.matifPrice || '',
      matifPriceCurrency: contract.financialInfo?.matifPriceCurrency || '',
      provisionalPrice: contract.financialInfo?.provisionalPrice || '',
      provisionalPriceCurrency: contract.financialInfo?.provisionalPriceCurrency || '',
      collateral: contract.financialInfo?.collateral || '',
      collateralCurrency: contract.financialInfo?.collateralCurrency || '',
      deposit: contract.financialInfo?.deposit || '',
      depositCurrency: contract.financialInfo?.depositCurrency || '',
      priceAdditionalMentions: contract.financialInfo?.priceAdditionalMentions || '',
      carryPrice1: contract.financialInfo?.carryPrice1 || '',
      carryPrice1Currency: contract.financialInfo?.carryPrice1Currency || '',
      carry: contract.financialInfo?.carry || '',
      carryCurrency: contract.financialInfo?.carryCurrency || ''
    },
    transportInfo: {
      incoterms: contract.delivery?.parity || '',
      deliveryPlace: contract.delivery?.locations?.[0]?.name || '',
      deliveryDateFrom: formatDate(deliveryStart) || '',
      deliveryDateTo: formatDate(deliveryEnd) || '',
      deliveryTermSBOption: contract.delivery?.deliveryTermSBOption || ''
    },
    documents: {
      contractDraft: contract.documents?.contractDraft || '',
      sellerSigned: contract.documents?.sellerSigned || '',
      buyerSigned: contract.documents?.buyerSigned || '',
      brokerSigned: contract.documents?.brokerSigned || ''
    },
    brokerInfo: {
      whoIsPayingCommission: contract.brokerInfo?.whoIsPayingCommission || '',
      sellerCommission: contract.general?.sellerBrokerCommission || '',
      sellerCommissionCurrency: contract.general?.sellerBrokerCommissionCurrency || '',
      buyerCommission: contract.general?.buyerBrokerCommission || '',
      buyerCommissionCurrency: contract.general?.buyerBrokerCommissionCurrency || ''
    },
    otherInfo: {
      pic: contract.pic || '',
      executionYear: contract.otherInfo?.executionYear || '',
      contractSignedStatus: contract.otherInfo?.contractSignedStatus || '',
      contractDateCheck: contract.otherInfo?.contractDateCheck || ''
    },
    payment: {
      type: contract.payment?.type || '',
      terms: contract.payment?.terms || '',
      moment: contract.payment?.moment || '',
      invoice: contract.payment?.invoice || ''
    },
    delivery: {
      parity: contract.delivery?.parity || '',
      locations: contract.delivery?.locations || [],
      transports: contract.delivery?.transports || [],
      conditions: contract.delivery?.conditions || ''
    },
    notes: contract.notes || ''
  }
}

export default function ContractDetailsPage() {
  const router = useRouter()
  const { t } = useTranslation()
  const [contract, setContract] = useState<any>({
    status: "Draft",
    brokerageCompany: "BNK",
    basicInfo: {},
    productInfo: {},
    financialInfo: {
      priceType: "Fixed"
    },
    payment: {},
    delivery: {
      locations: [{ name: "Constanta", value: "0", currency: "EUR" }], // Predefined first location
      transports: [], // New array to store transport details
    },
    notes: ""
  })
  const [loading, setLoading] = useState(true)
  const [companies, setCompanies] = useState<string[]>([])
  const [productCode, setProductCode] = useState<string[]>([])
  const [cropYear, setCropYear] = useState<string[]>([])
  const [origin, setOrigin] = useState<string[]>([])
  const [selectedCompany, setSelectedCompany] = useState<string>("")
  const [selectedBuyerCompany, setSelectedBuyerCompany] = useState<string>("")
  const [selectedProductCode, setSelectedProductCode] = useState<string>("")
  const [selectedCropYear, setSelectedCropYear] = useState<string>("")
  const [selectedOrigin, setSelectedOrigin] = useState<string>("")
  const [currentTab, setCurrentTab] = useState("general")
  const [isMobile, setIsMobile] = useState(false)
  const [isMobileCheckComplete, setIsMobileCheckComplete] = useState(false)
  const [showCompanyDialog, setShowCompanyDialog] = useState(false)
  const [newCompanyName, setNewCompanyName] = useState("")
  const [isCreatingCompany, setIsCreatingCompany] = useState(false)
  const [companyNotes, setCompanyNotes] = useState<Record<string, { buyerNote: string; sellerNote: string }>>({})
  const [locationOptions] = useState([
    { value: "Constanta", label: "Constanta, CT" },
    { value: "Bucuresti", label: "Bucuresti, B" },
    { value: "Brasov", label: "Brasov, BV" },
    { value: "Iasi", label: "Iasi, I" },
    { value: "Cluj Napoca", label: "Cluj Napoca, CJ" }
  ])

  const [parityOptions] = useState([
    { value: "FCA", label: "FCA" },
    { value: "DAP", label: "DAP" },
    { value: "FOB", label: "FOB" },
    { value: "CIF", label: "CIF" },
    { value: "CIFFO", label: "CIFFO" },
    { value: "CPT", label: "CPT" },
    { value: "DAP/CIF", label: "DAP/CIF" },
    { value: "DAP/FOB", label: "DAP/FOB" },
    { value: "DDP", label: "DDP" },
    { value: "EXW", label: "EXW" },
    { value: "CIF/DAP", label: "CIF/DAP" },
    { value: "DAP/CIFFO", label: "DAP/CIFFO" },
    { value: "CIFFO/DAP", label: "CIFFO/DAP" },
    { value: "DAP/FCA", label: "DAP/FCA" },
    { value: "FCA/DAP", label: "FCA/DAP" },
    { value: "TRP", label: "TRP" }
  ])

  const incotermOptionsMapping: { [key: string]: { quantity: string; quality: string; deliveryPeriod: string; meanOfTransport: string; deliveryPlace: string; } } = {
    "CIF": { quantity: "S", quality: "S", deliveryPeriod: "S", meanOfTransport: "S", deliveryPlace: "B" },
    "CIFFO": { quantity: "S", quality: "S", deliveryPeriod: "S", meanOfTransport: "S", deliveryPlace: "B" },
    "CPT": { quantity: "S", quality: "S", deliveryPeriod: "S", meanOfTransport: "S", deliveryPlace: "B" },
    "DAP": { quantity: "S", quality: "S", deliveryPeriod: "S", meanOfTransport: "S", deliveryPlace: "B" },
    "DAP/CIF": { quantity: "S/S", quality: "S", deliveryPeriod: "S/S", meanOfTransport: "S/S", deliveryPlace: "B/B" },
    "DAP/FOB": { quantity: "S/B", quality: "S", deliveryPeriod: "S/B", meanOfTransport: "S/B", deliveryPlace: "B/S" },
    "DDP": { quantity: "S", quality: "S", deliveryPeriod: "S", meanOfTransport: "S", deliveryPlace: "B" },
    "EXW": { quantity: "S", quality: "S", deliveryPeriod: "S", meanOfTransport: "S", deliveryPlace: "S" },
    "FCA": { quantity: "B", quality: "S", deliveryPeriod: "B", meanOfTransport: "B", deliveryPlace: "S" },
    "FOB": { quantity: "B", quality: "S", deliveryPeriod: "B", meanOfTransport: "B", deliveryPlace: "S" },
    "CIF/DAP": { quantity: "B/S", quality: "S", deliveryPeriod: "B/S", meanOfTransport: "B/S", deliveryPlace: "S/B" },
    "DAP/CIFFO": { quantity: "S/S", quality: "S", deliveryPeriod: "S/S", meanOfTransport: "S/S", deliveryPlace: "B/B" },
    "CIFFO/DAP": { quantity: "S/S", quality: "S", deliveryPeriod: "S/S", meanOfTransport: "S/S", deliveryPlace: "B/B" },
    "DAP/FCA": { quantity: "S/B", quality: "S", deliveryPeriod: "S/B", meanOfTransport: "S/B", deliveryPlace: "B/S" },
    "FCA/DAP": { quantity: "B/S", quality: "S", deliveryPeriod: "B/S", meanOfTransport: "B/S", deliveryPlace: "B/S" },
    "TRP": { quantity: "B", quality: "B", deliveryPeriod: "B", meanOfTransport: "B", deliveryPlace: "B" },
  };

  const [transportOptions] = useState([
    { value: "by truck", label: "TR" },
    { value: "by wagons", label: "WA" },
    { value: "by barge", label: "BA" },
    { value: "TR / WA", label: "TR / WA" },
    { value: "TR / WA / VS", label: "TR / WA / VS" },
    { value: "TR / WA / EXW", label: "TR / WA / EXW" },
    { value: "BA / VS", label: "BA / VS" }
  ])

  const [paymentTypeOptions] = useState([
    { value: "CAD", label: "CAD" },
    { value: "Avans", label: "Avans" },
    { value: "CD", label: "CD" },
    { value: "BO", label: "BO" }
  ])

  const [paymentTermsOptions] = useState({
    CAD: [
      { value: "CAD 2", label: "CAD 2" },
      { value: "CAD 3", label: "CAD 3" },
      { value: "CAD 5", label: "CAD 5" },
      { value: "CAD 7", label: "CAD 7" },
      { value: "CAD 10", label: "CAD 10" },
    ],
    Avans: [
      { value: "AVANS 100%", label: "AVANS 100%" },
      { value: "AVANS 95%", label: "AVANS 95%" },
      { value: "AVANS 90%", label: "AVANS 90%" },
      { value: "AVANS 85%", label: "AVANS 85%" },
      { value: "AVANS 80%", label: "AVANS 80%" },
      { value: "AVANS 70%", label: "AVANS 70%" },
    ],
    CD: [
      { value: "CD98%", label: "CD98%" },
      { value: "CD95%", label: "CD95%" },
      { value: "CD90%", label: "CD90%" },
      { value: "CD85%", label: "CD85%" },
      { value: "CD80%", label: "CD80%" },
    ],
    BO: [
      { value: "BO 30 DAYS", label: "BO 30 DAYS" },
      { value: "BO 45 DAYS", label: "BO 45 DAYS" },
      { value: "BO 60 DAYS", label: "BO 60 DAYS" },
      { value: "BO 90 DAYS", label: "BO 90 DAYS" }
    ]
  });

  const paymentDetailsMap: { [key: string]: { [key: string]: Array<{ moment: string; invoice: string; }> } } = {
    "Avans": {
      "AVANS 100%": [
        { moment: "Before Loading", invoice: "Advance invoice" },
        { moment: "After loading", invoice: "Advance invoice" },
        { moment: "After loading", invoice: "Proforma invoice" }
      ],
      "AVANS 95%": [
        { moment: "Before Loading", invoice: "Advance invoice" },
        { moment: "After loading", invoice: "Advance invoice" },
        { moment: "After loading", invoice: "Proforma invoice" }
      ],
      "AVANS 90%": [
        { moment: "Before Loading", invoice: "Advance invoice" },
        { moment: "After loading", invoice: "Advance invoice" },
        { moment: "After loading", invoice: "Proforma invoice" }
      ],
      "AVANS 85%": [
        { moment: "Before Loading", invoice: "Advance invoice" },
        { moment: "After loading", invoice: "Advance invoice" },
        { moment: "After loading", invoice: "Proforma invoice" }
      ],
      "AVANS 80%": [
        { moment: "Before Loading", invoice: "Advance invoice" },
        { moment: "After loading", invoice: "Advance invoice" },
        { moment: "After loading", invoice: "Proforma invoice" }
      ],
      "AVANS 70%": [
        { moment: "Before Loading", invoice: "Advance invoice" },
        { moment: "After loading", invoice: "Advance invoice" },
        { moment: "After loading", invoice: "Proforma invoice" }
      ]
    },
    "BO": {
      "BO 30 DAYS": [{ moment: "After Discharge", invoice: "Commercial invoice" }],
      "BO 45 DAYS": [{ moment: "After Discharge", invoice: "Commercial invoice" }],
      "BO 60 DAYS": [{ moment: "After Discharge", invoice: "Commercial invoice" }],
      "BO 90 DAYS": [{ moment: "After Discharge", invoice: "Commercial invoice" }]
    },
    "CAD": {
      "CAD 10": [
        { moment: "After loading", invoice: "Commercial invoice" },
        { moment: "Before Discharge", invoice: "Commercial invoice" },
        { moment: "After Discharge", invoice: "Commercial invoice" }
      ],
      "CAD 2": [
        { moment: "After loading", invoice: "Commercial invoice" },
        { moment: "Before Discharge", invoice: "Commercial invoice" },
        { moment: "After Discharge", invoice: "Commercial invoice" }
      ],
      "CAD 3": [
        { moment: "After loading", invoice: "Commercial invoice" },
        { moment: "Before Discharge", invoice: "Commercial invoice" },
        { moment: "After Discharge", invoice: "Commercial invoice" }
      ],
      "CAD 5": [
        { moment: "After loading", invoice: "Commercial invoice" },
        { moment: "Before Discharge", invoice: "Commercial invoice" },
        { moment: "After Discharge", invoice: "Commercial invoice" }
      ],
      "CAD 7": [
        { moment: "After loading", invoice: "Commercial invoice" },
        { moment: "Before Discharge", invoice: "Commercial invoice" },
        { moment: "After Discharge", invoice: "Commercial invoice" }
      ]
    },
    "CD": {
      "CD80%": [{ moment: "Before Loading", invoice: "Commercial invoice" }],
      "CD85%": [{ moment: "Before Loading", invoice: "Commercial invoice" }],
      "CD90%": [{ moment: "Before Loading", invoice: "Commercial invoice" }],
      "CD95%": [{ moment: "Before Loading", invoice: "Commercial invoice" }],
      "CD98%": [{ moment: "Before Loading", invoice: "Commercial invoice" }]
    }
  };

  const [invoiceOptions] = useState([
    { value: "Commercial invoice", label: "Commercial invoice" },
    { value: "Advance", label: "Advance" }
  ]);

  const [toleranceOptions] = useState({
    percentage: [
      { value: "2", label: "2%" },
      { value: "5", label: "5%" },
      { value: "10", label: "10%" },
      
    ],
    tonnage: [
      { value: "25", label: "25 to" }
    ],
    minmax: [{ value: "min/max", label: "min/max" }]
  })

  const [quantityOptions, setQuantityOptions] = useState<Array<{ value: string; label: string }>>([
    { value: "1000", label: "1000" },
    { value: "1500", label: "1500" },
    { value: "3000", label: "3000" }
  ])

  const [showSendDialog, setShowSendDialog] = useState(false)
  const [selectedRecipientType, setSelectedRecipientType] = useState<string>("")

  const [qualityOptions, setQualityOptions] = useState<Array<{ value: string; label: string }>>([])

  const [partners, setPartners] = useState<any[]>([])
  const [companyOptions, setCompanyOptions] = useState<{ value: string; label: string }[]>([])

  const [products, setProducts] = useState<Array<{
    code: string;
    goods: string;
    cropYear: string;
    origin: string;
    qualityParameters: Array<{ name: string }>;
  }>>([])
  const [cropYears, setCropYears] = useState<Array<{ year: string }>>([])
  const [origins, setOrigins] = useState<Array<{ name: string; fullENG?: string }>>([])
  const [selectedProduct, setSelectedProduct] = useState<{
    code: string;
    goods: string;
    cropYear: string;
    origin: string;
    qualityParameters: Array<{ name: string }>;
  } | null>(null)

  const handleCompanySelect = (value: string, isSeller: boolean) => {
    const selectedPartner = partners.find(p => p.idPartner === value);
    if (selectedPartner) {
      if (isSeller) {
        setSelectedCompany(value);
        setContract({ 
          ...contract, 
          basicInfo: { 
            ...contract.basicInfo, 
            sellerCompany: value 
          },
          general: {
            ...contract.general,
            sellerVat: selectedPartner.vatNo
          }
        });
      } else {
        setSelectedBuyerCompany(value);
        setContract({ 
          ...contract, 
          basicInfo: { 
            ...contract.basicInfo, 
            buyerCompany: value 
          },
          general: {
            ...contract.general,
            buyerVat: selectedPartner.vatNo
          }
        });
      }
    }
  };

  useEffect(() => {
    const fetchData = async () => {
      try {
        // Fetch products
        const productsResponse = await fetch('/products/api/productsdata');
        const productsData = await productsResponse.json();
        setProducts(productsData);

        // Fetch crop years
        const cropYearsResponse = await fetch('/products/api/cropyears');
        const cropYearsData = await cropYearsResponse.json();
        setCropYears(cropYearsData);

        // Fetch origins
        const originsResponse = await fetch('/products/api/origins');
        const originsData = await originsResponse.json();
        setOrigins(originsData);

        // Fetch partners
        const partnersResponse = await fetch('/partners/api');
        const partnersData = await partnersResponse.json();
        setPartners(partnersData);
        
        // Create company options from partners data
        const options = partnersData.map((partner: any) => ({
          value: partner.idPartner,
          label: partner.companyName
        })).sort((a: any, b: any) => a.label.localeCompare(b.label));
        setCompanyOptions(options);
      } catch (error) {
        console.error('Error fetching data:', error);
      } finally {
        setLoading(false);
      }
    };

    // Check if mobile
    const checkMobile = () => {
      setIsMobile(window.innerWidth < 768);
      setIsMobileCheckComplete(true);
    };
    checkMobile();
    window.addEventListener('resize', checkMobile);

    fetchData();

    return () => {
      window.removeEventListener('resize', checkMobile);
    };
  }, []);

  const handleProductCodeChange = (value: string) => {
    if (!value) return; // Skip if empty value
    
    const product = products.find(p => p.code === value);
    setSelectedProduct(product || null);
    if (product) {
      // Update quality options based on selected product
      const qualityParams = product.qualityParameters.map(param => param.name);
      setQualityOptions(qualityParams.map(param => ({ value: param, label: param })));
      
      // Update contract with product details
      setContract({
        ...contract,
        productInfo: {
          ...contract.productInfo,
          code: product.code || '',
          name: product.goods || '',
          quality: qualityParams[0] || '',
          cropYear: product.cropYear || '',
          origin: product.origin || ''
        }
      });
    }
  };

  const productCodeOptions = products.map(product => ({ 
    value: product.code || 'unknown', 
    label: `${product.code || ''}` 
  })).filter(option => option.value && option.value !== 'unknown');

  const cropYearOptions = cropYears
    .map(year => ({ 
      value: year.year || 'unknown', 
      label: year.year || '' 
    }))
    .filter(option => option.value && option.value !== 'unknown');

  const originOptions = origins
    .map(origin => ({ 
      value: origin.name || 'unknown', 
      label: origin.fullENG || origin.name || '' 
    }))
    .filter(option => option.value && option.value !== 'unknown');

  const qualityOptionsList = [
    { value: "", label: t("bizz.selectQuality") },
    ...qualityOptions.map(quality => ({ 
      value: quality.value, 
      label: quality.label 
    }))
  ]

  const handleBack = () => {
    if (window.history.length > 1) {
      router.back()
    } else {
      router.push("/contracts/bizz")
    }
  }

  const handleSave = async () => {
    const mergedContract = {
      ...contract,
      basicInfo: {
        ...contract.basicInfo,
        sellerCompany: selectedCompany,
        buyerCompany: selectedBuyerCompany,
        buyerNote: companyNotes[selectedBuyerCompany]?.buyerNote || "",
        sellerNote: companyNotes[selectedCompany]?.sellerNote || ""
      },
      pic: contract.pic || "",
      brokerageCompany: contract.brokerageCompany || "BNK",
      notes: contract.notes || ""
    }
    
    // Get next ID and add it to the contract
    const nextId = await getNextId();
    mergedContract.id = nextId;
    
    // Map to full structure
    const fullContract = mapToFullContract(mergedContract, selectedCompany, selectedBuyerCompany, companyNotes)
    try {
      const response = await fetch('/contracts/api/contractsdata', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(fullContract)
      })
      if (!response.ok) throw new Error('Failed to save contract')
      alert('Contract created successfully!')
      router.push("/contracts/bizz")
    } catch (error) {
      alert('Failed to create contract.')
    }
  }

  const handleSend = async () => {
    if (!selectedRecipientType) {
      alert('Please select a recipient type')
      return
    }
    const mergedContract = {
      ...contract,
      basicInfo: {
        ...contract.basicInfo,
        sellerCompany: selectedCompany,
        buyerCompany: selectedBuyerCompany,
        buyerNote: companyNotes[selectedBuyerCompany]?.buyerNote || "",
        sellerNote: companyNotes[selectedCompany]?.sellerNote || ""
      },
      pic: contract.pic || "",
      brokerageCompany: contract.brokerageCompany || "BNK",
      notes: contract.notes || ""
    }
    
    // Get next ID and add it to the contract
    const nextId = await getNextId();
    mergedContract.id = nextId;
    
    // Map to full structure
    const fullContract = mapToFullContract(mergedContract, selectedCompany, selectedBuyerCompany, companyNotes)
    try {
      const saveResponse = await fetch('/contracts/api/contractsdata', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(fullContract)
      })
      if (!saveResponse.ok) throw new Error('Failed to save contract')
      alert('Contract saved successfully!')
      setShowSendDialog(false)
      router.push('/contracts/bizz')
    } catch (error) {
      alert('Failed to save contract.')
    }
  }

  const handleSendClick = () => {
    setShowSendDialog(true)
  }

  const handleNext = () => {
    const tabs = ["general", "product", "delivery-condition", "payment", "delivery", "price", "notes"]
    const currentIndex = tabs.indexOf(currentTab)
    if (currentIndex < tabs.length - 1) {
      setCurrentTab(tabs[currentIndex + 1])
    }
  }

  const handlePrevious = () => {
    const tabs = ["general", "product", "delivery-condition", "payment", "delivery", "price", "notes"]
    const currentIndex = tabs.indexOf(currentTab)
    if (currentIndex > 0) {
      setCurrentTab(tabs[currentIndex - 1])
    }
  }

  const getStatusBadge = (status: string) => (
    <Badge variant="outline" className="text-muted-foreground px-1.5">
      {status.toLowerCase() === "open" ? (
        <IconCircleCheckFilled className="fill-green-500 dark:fill-green-400 mr-2" />
      ) : status.toLowerCase() === "pending" ? (
        <IconLoader className="mr-2" />
      ) : (
        <IconCircleCheckFilled className="fill-gray-500 dark:fill-gray-400 mr-2" />
      )}
      {status}
    </Badge>
  )

  const handleCreateCompany = async (companyName: string) => {
    if (!companyName.trim()) return
    
    setIsCreatingCompany(true);
    try {
      const updatedCompanies = [...companies, companyName];
      setCompanies(updatedCompanies);
      setSelectedCompany(companyName);
      setShowCompanyDialog(false);
      setNewCompanyName("");
    } catch (error) {
      alert('Failed to create company');
    } finally {
      setIsCreatingCompany(false);
    }
  };

  const getTabTitle = (tab: string) => {
    switch(tab) {
      case "general": return t("bizz.general");
      case "product": return t("bizz.product");
      case "delivery-condition": return t("bizz.deliverycondition");
      case "payment": return t("bizz.paymentterms");
      case "delivery": return t("bizz.deliveryperiod");
      case "price": return t("bizz.price");
      case "notes": return t("bizz.notes");
      default: return "";
    }
  };

  const getDeliveryConditionText = (parity: string, transports: Array<{ type: string }>) => {
    if (!transports || transports.length === 0) return "";

    const transportTexts = transports.map(transport => {
      switch(parity) {
        case "FCA":
          return `In cazul livrarilor folosind transportul ${transport.type} si incoterms FCA, marfa va fi livrata la adresa furnizorului.`;
        case "DAP":
          return `In cazul livrarilor folosind transportul ${transport.type} si incoterms DAP, marfa va fi livrata la adresa destinatarului.`;
        case "FOB":
          return `In cazul livrarilor folosind transportul ${transport.type} si incoterms FOB, marfa va fi livrata la portul de incarcare.`;
        case "CIF":
          return `In cazul livrarilor folosind transportul ${transport.type} si incoterms CIF, marfa va fi livrata la portul de descarcare.`;
        default:
          return "";
      }
    }).filter(text => text !== "");

    return transportTexts.join("\n");
  };

  useEffect(() => {
    if (contract.delivery?.parity && contract.delivery?.transports) {
      const conditionText = getDeliveryConditionText(contract.delivery.parity, contract.delivery.transports);
      setContract({
        ...contract,
        delivery: {
          ...contract.delivery,
          conditions: conditionText
        }
      });
    }
  }, [contract.delivery?.parity, contract.delivery?.transports]);

  if (loading) return <div className="p-8">Loading not finished...</div>
  if (!isMobileCheckComplete) return <div className="p-8">Loading...</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="contractlist.bizzcontract" />
        <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">{t("bizz.title")}</h2>
                {getStatusBadge(contract.status)}
              </div>
              <div className="flex gap-2">
                <Button variant="outline" onClick={handleBack}>{t("bizz.back")}</Button>
              </div>
            </div>

            {/* Mobile Tab Indicator */}
            {isMobile && (
              <div className="px-4 w-full h-12">
                <div className="bg-muted text-muted-foreground inline-flex h-12 w-full items-center justify-center rounded-lg p-[3px]">
                  <div className="data-[state=active]:bg-background dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-lg font-bold whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4">
                    {currentTab === "general" && <BuildingIcon className="h-4 w-4" />}
                    {currentTab === "product" && <IconPackage className="h-4 w-4" />}
                    {currentTab === "delivery-condition" && <Scale className="h-4 w-4" />}
                    {currentTab === "payment" && <DollarIcon className="h-4 w-4" />}
                    {currentTab === "delivery" && <Scale className="h-4 w-4" />}
                    {currentTab === "price" && <DollarIcon className="h-4 w-4" />}
                    {currentTab === "notes" && <IconPackage className="h-4 w-4" />}
                    {getTabTitle(currentTab)}
                  </div>
                </div>
              </div>
            )}

            <Tabs value={currentTab} onValueChange={setCurrentTab} className="w-full">
              
              {!isMobile && (
                <TabsList className="px-4 lg:px-6 lg:w-full lg:h-14">
                  <TabsTrigger value="general" className="flex items-center gap-2 lg:text-lg">
                    <BuildingIcon className="h-4 w-4" />
                    {t("bizz.general")}
                  </TabsTrigger>
                  <TabsTrigger value="product" className="flex items-center gap-2 lg:text-lg">
                    <IconPackage className="h-4 w-4" />
                    {t("bizz.product")}
                  </TabsTrigger>
                   <TabsTrigger value="delivery-condition" className="flex items-center gap-2 lg:text-lg">
                    <Scale className="h-4 w-4" />
                    {t("bizz.deliverycondition")}
                  </TabsTrigger>
                  <TabsTrigger value="payment" className="flex items-center gap-2 lg:text-lg">
                    <DollarIcon className="h-4 w-4" />
                    {t("bizz.paymentterms")}
                  </TabsTrigger>
                  <TabsTrigger value="delivery" className="flex items-center gap-2 lg:text-lg">
                    <Scale className="h-4 w-4" />
                    {t("bizz.deliveryperiod")}
                  </TabsTrigger>
                  <TabsTrigger value="price" className="flex items-center gap-2 lg:text-lg">
                    <DollarIcon className="h-4 w-4" />
                    {t("bizz.price")}
                  </TabsTrigger>
                  <TabsTrigger value="notes" className="flex items-center gap-2 lg:text-lg">
                    <IconPackage className="h-4 w-4" />
                    {t("bizz.notes")}
                  </TabsTrigger>
                </TabsList>
              )}

              <div className={isMobile ? "block" : "contents"}>
                <TabsContent 
                  value="general" 
                  className="px-4 lg:px-6"
                  style={{ display: isMobile && currentTab !== "general" ? "none" : "block" }}
                >
                  <Card>
                    <CardHeader>
                      <CardTitle className="flex items-center gap-2">
                        <BuildingIcon className="h-5 w-5" />
                        {t("bizz.general")}
                      </CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-4">
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div  className="grid grid-cols-1 md:grid-cols-2 gap-4"> 
                          <div className="flex flex-col gap-2">
                          <span className="font-medium">Broker Company</span>
                            <Select
                              value={contract.brokerageCompany || "BNK"}
                              onValueChange={(value) => {
                                setContract({ 
                                  ...contract, 
                                  brokerageCompany: value 
                                });
                              }}
                            >
                              <SelectTrigger>
                                <SelectValue placeholder="Select broker company" />
                              </SelectTrigger>
                              <SelectContent>
                                <SelectItem value="BNK">BNK</SelectItem>
                                <SelectItem value="BRO">BRO</SelectItem>
                                <SelectItem value="SMA">SMA</SelectItem>
                              </SelectContent>
                            </Select>
                          </div>
                          <div className="flex flex-col gap-2">
                          <span className="font-medium">Bizz Conf Template</span>
                            <Select
                              value={contract.brokerageCompany || "Template 1"}
                              onValueChange={(value) => {
                                setContract({ 
                                  ...contract, 
                                  brokerageCompany: value 
                                });
                              }}
                            >
                              <SelectTrigger>
                                <SelectValue placeholder="Select broker company" />
                              </SelectTrigger>
                              <SelectContent>
                                <SelectItem value="BNK">Template 1</SelectItem>
                                <SelectItem value="BRO">Template 2</SelectItem>
                                <SelectItem value="SMA">Template 3</SelectItem>
                              </SelectContent>
                            </Select>
                          </div>
                        
                        </div>
                        
                        <div className="flex flex-col gap-2">
                        <span className="font-medium">Assigned broker</span>
                          <Select
                            value={contract.pic || ""}
                            onValueChange={(value) => {
                              setContract({ 
                                ...contract, 
                                pic: value 
                              });
                            }}
                          >
                            <SelectTrigger>
                              <SelectValue placeholder="Select broker" />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="Simona Plesea">SP</SelectItem>
                              <SelectItem value="Mihai Birladeanu">MB</SelectItem>
                              <SelectItem value="Bogdan Banica">BB</SelectItem>
                              <SelectItem value="Alexandra Chirita">AC</SelectItem>
                              <SelectItem value="Ruxandra Bogdan">RB</SelectItem>
                            </SelectContent>
                          </Select>
                        </div>
                        <div className="flex flex-col gap-2">
                          <span className="font-medium">{t("bizz.seller")}</span>
                          <div className="flex gap-2">
                            <div className="flex-1">
                              <ComboboxFull 
                                items={companyOptions}
                                value={selectedCompany}
                                onValueChange={(value) => handleCompanySelect(value, true)}
                                placeholder={t("bizz.selectCompany")}
                                emptyText={t("bizz.noCompanies")}
                                showCreateOption={true}
                                onCreateNew={handleCreateCompany}
                              />
                            </div>
                          </div>
                        </div>
                        <div className="flex flex-col gap-2">
                          <span className="font-medium">{t("bizz.sellerVATno")}</span>
                          <Input 
                            value={contract.general?.sellerVat || "-"} 
                            onChange={e => setContract({ ...contract, general: { ...contract.general, sellerVat: e.target.value } })}
                            readOnly
                          />
                        </div>
                       
                        <div className="flex flex-col gap-2">
                          <span className="font-medium">{t("bizz.buyer")}</span>
                          <div className="flex gap-2">
                            <div className="flex-1">
                              <ComboboxFull 
                                items={companyOptions}
                                value={selectedBuyerCompany}
                                onValueChange={(value) => handleCompanySelect(value, false)}
                                placeholder={t("bizz.selectCompany")}
                                emptyText={t("bizz.noCompanies")}
                                showCreateOption={true}
                                onCreateNew={handleCreateCompany}
                              />
                            </div>
                          </div>
                        </div>
                        <div className="flex flex-col gap-2">
                          <span className="font-medium">{t("bizz.buyerVATno")}</span>
                          <Input 
                            value={contract.general?.buyerVat || "-"} 
                            onChange={e => setContract({ ...contract, general: { ...contract.general, buyerVat: e.target.value } })}
                            readOnly
                          />
                        </div>

                        
                        
                        {contract.brokerageCompany !== "SMA" && (
                          <div className="flex flex-col gap-2">
                            <span className="font-medium">Broker's commission (Seller)</span>
                            <div className="flex gap-2">
                              <Input value={contract.general?.sellerBrokerCommission || " "} onChange={e => setContract({ ...contract, general: { ...contract.general, sellerBrokerCommission: e.target.value } })} className="w-1/2" />
                              <Select value={contract.general?.sellerBrokerCommissionCurrency || "EUR"} onValueChange={val => setContract({ ...contract, general: { ...contract.general, sellerBrokerCommissionCurrency: val } })}>
                                <SelectTrigger className="w-full">
                                  <SelectValue />
                                </SelectTrigger>
                                <SelectContent>
                                  <SelectItem value="EUR">EUR</SelectItem>
                                  <SelectItem value="USD">USD</SelectItem>
                                  <SelectItem value="RON">RON</SelectItem>
                                </SelectContent>
                              </Select>
                            
                            <Select value={contract.general?.sellerBrokerCode || ""} onValueChange={val => setContract({ ...contract, general: { ...contract.general, sellerBrokerCode: val } })}>
                              <SelectTrigger>
                                <SelectValue placeholder="Select seller broker code" />
                              </SelectTrigger>
                              <SelectContent>
                                <SelectItem value="SP">SP</SelectItem>
                                <SelectItem value="MB">MB</SelectItem>
                                <SelectItem value="BB">BB</SelectItem>
                                <SelectItem value="AC">AC</SelectItem>
                                <SelectItem value="RB">RB</SelectItem>
                              </SelectContent>
                            </Select>
                            </div>
                          </div>
                        )}
                        {contract.brokerageCompany !== "SMA" && (
                          <div className="flex flex-col gap-2">
                            <span className="font-medium">Broker's commission (Buyer)</span>
                            <div className="flex gap-2">
                              <Input value={contract.general?.buyerBrokerCommission || " "} onChange={e => setContract({ ...contract, general: { ...contract.general, buyerBrokerCommission: e.target.value } })} className="w-1/2" />
                              <Select value={contract.general?.buyerBrokerCommissionCurrency || "USD"} onValueChange={val => setContract({ ...contract, general: { ...contract.general, buyerBrokerCommissionCurrency: val } })}>
                                <SelectTrigger className="w-full">
                                  <SelectValue />
                                </SelectTrigger>
                                <SelectContent>
                                  <SelectItem value="EUR">EUR</SelectItem>
                                  <SelectItem value="USD">USD</SelectItem>
                                  <SelectItem value="RON">RON</SelectItem>
                                </SelectContent>
                              </Select>
                            
                            <Select value={contract.general?.buyerBrokerCode || ""} onValueChange={val => setContract({ ...contract, general: { ...contract.general, buyerBrokerCode: val } })}>
                              <SelectTrigger>
                                <SelectValue placeholder="Select buyer broker code" />
                              </SelectTrigger>
                              <SelectContent>
                                <SelectItem value="SP">SP</SelectItem>
                                <SelectItem value="MB">MB</SelectItem>
                                <SelectItem value="BB">BB</SelectItem>
                                <SelectItem value="AC">AC</SelectItem>
                                <SelectItem value="RB">RB</SelectItem>
                              </SelectContent>
                            </Select>
                            </div>
                          </div>
                        )}

                      
                        
                      </div>
                    </CardContent>
                  </Card>
                </TabsContent>

                <TabsContent 
                  value="product" 
                  className="px-4 lg:px-6"
                  style={{ display: isMobile && currentTab !== "product" ? "none" : "block" }}
                >
                  <Card>
                    <CardHeader>
                      <CardTitle className="flex items-center gap-2">
                        <IconPackage className="h-5 w-5" />
                        {t("bizz.product")}
                      </CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-4">
                      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
                        <div className="flex flex-col gap-2">
                          <span className="font-medium">{t("bizz.productCode")}</span>
                          <ComboboxFull 
                            items={productCodeOptions}
                            value={contract.productInfo?.code || ""}
                            onValueChange={handleProductCodeChange}
                            placeholder={t("bizz.selectProductCode")}
                            emptyText={t("bizz.noProductCodes")}
                            showCreateOption={true}
                            onCreateNew={(value) => {
                              setProductCode([...productCode, value]);
                              setSelectedProductCode(value);
                            }}
                          />
                        </div>
                        <div className="flex flex-col gap-2">
                          <span className="font-medium">{t("bizz.product")}</span>
                          <Input value={contract.productInfo?.name || "-"} readOnly />
                        </div>
                        <div className="flex flex-col gap-2">
                          <span className="font-medium">{t("bizz.cropYear")}</span>
                          <ComboboxFull 
                            items={cropYearOptions}
                            value={contract.productInfo?.cropYear || ""}
                            onValueChange={(value) => {
                              setContract({
                                ...contract,
                                productInfo: {
                                  ...contract.productInfo,
                                  cropYear: value
                                }
                              });
                            }}
                            placeholder={t("bizz.selectCropYear")}
                            emptyText={t("bizz.noCropYears")}
                            showCreateOption={true}
                            onCreateNew={(value) => {
                              setCropYear([...cropYear, value]);
                              setSelectedCropYear(value);
                            }}
                          />
                        </div>
                        <div className="flex flex-col gap-2">
                          <span className="font-medium">{t("bizz.origin")}</span>
                          <ComboboxFull 
                            items={originOptions}
                            value={contract.productInfo?.origin || ""}
                            onValueChange={(value) => {
                              setContract({
                                ...contract,
                                productInfo: {
                                  ...contract.productInfo,
                                  origin: value
                                }
                              });
                            }}
                            placeholder={t("bizz.selectOrigin")}
                            emptyText={t("bizz.noOrigins")}
                            showCreateOption={true}
                            onCreateNew={(value) => {
                              setOrigin([...origin, value]);
                              setSelectedOrigin(value);
                            }}
                          />
                        </div>
                      </div>
                      <div className="border rounded p-4 mt-2 bg-muted/100">
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                          <div className="flex flex-col gap-2">
                            <span className="font-medium">Quantity</span>
                            <Input 
                              type="number"
                              value={contract.productInfo?.quantity || ""} 
                              onChange={e => setContract({
                                ...contract,
                                productInfo: {
                                  ...contract.productInfo,
                                  quantity: e.target.value
                                }
                              })}
                              placeholder="Enter quantity"
                            />
                          </div>
                          <div className="flex flex-col gap-2">
                            <span className="font-medium">UM</span>
                            <Select value={contract.productInfo?.unit || "to"} onValueChange={val => setContract({ ...contract, productInfo: { ...contract.productInfo, unit: val } })}>
                              <SelectTrigger>
                                <SelectValue />
                              </SelectTrigger>
                              <SelectContent>
                                <SelectItem value="to">to</SelectItem>
                                <SelectItem value="serv">serv</SelectItem>
                              </SelectContent>
                            </Select>
                          </div>
                          <div className="flex flex-col gap-2">
                            <span className="font-medium">Tolerance</span>
                            <div className="flex gap-2">
                              <Select 
                                value={contract.productInfo?.toleranceType || "percentage"} 
                                onValueChange={val => {
                                  const defaultTolerance = val === "percentage" ? "5" : val === "tonnage" ? "25" : "min/max";
                                  setContract({ 
                                    ...contract, 
                                    productInfo: { 
                                      ...contract.productInfo, 
                                      toleranceType: val,
                                      tolerance: defaultTolerance
                                    } 
                                  });
                                }}
                              >
                                <SelectTrigger className="w-1/2">
                                  <SelectValue />
                                </SelectTrigger>
                                <SelectContent>
                                  <SelectItem value="percentage">%</SelectItem>
                                  <SelectItem value="tonnage">to</SelectItem>
                                  <SelectItem value="minmax">min/max</SelectItem>
                                </SelectContent>
                              </Select>
                              {contract.productInfo?.toleranceType !== "minmax" && (
                                <Select 
                                  value={contract.productInfo?.tolerance || (contract.productInfo?.toleranceType === "percentage" ? "5" : "25")} 
                                  onValueChange={val => setContract({ 
                                    ...contract, 
                                    productInfo: { 
                                      ...contract.productInfo, 
                                      tolerance: val 
                                    } 
                                  })}
                                >
                                  <SelectTrigger className="w-1/2">
                                    <SelectValue />
                                  </SelectTrigger>
                                  <SelectContent>
                                    {contract.productInfo?.toleranceType === "percentage" ? (
                                      toleranceOptions.percentage.map(option => (
                                        <SelectItem key={option.value} value={option.value}>
                                          {option.label}
                                        </SelectItem>
                                      ))
                                    ) : (
                                      toleranceOptions.tonnage.map(option => (
                                        <SelectItem key={option.value} value={option.value}>
                                          {option.label}
                                        </SelectItem>
                                      ))
                                    )}
                                  </SelectContent>
                                </Select>
                              )}
                            </div>
                          </div>
                          <div className="flex flex-col gap-2">
                            <span className="font-medium">Option</span>
                            <Select value={contract.productInfo?.quantityOption || "Seller"} onValueChange={val => setContract({ ...contract, productInfo: { ...contract.productInfo, quantityOption: val } })}>
                              <SelectTrigger>
                                <SelectValue />
                              </SelectTrigger>
                              <SelectContent>
                                <SelectItem value="Seller">S</SelectItem>
                                <SelectItem value="Buyer">B</SelectItem>
                              </SelectContent>
                            </Select>
                          </div>
                          <div className="flex flex-col gap-2">
                            <span className="font-medium">{t("bizz.finalAt")}</span>
                            <Select value={contract.productInfo?.finalAt || "Loading"} onValueChange={val => setContract({ ...contract, productInfo: { ...contract.productInfo, finalAt: val } })}>
                              <SelectTrigger>
                                <SelectValue />
                              </SelectTrigger>
                              <SelectContent>
                                <SelectItem value="Loading">Loading</SelectItem>
                                <SelectItem value="Discharge">Discharge</SelectItem>
                              </SelectContent>
                            </Select>
                          </div>
                        </div>
                      </div>
                      <div className="border rounded p-4 mt-2 bg-muted/100">
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                          <div className="flex flex-col gap-2">
                            <span className="font-medium">Quality</span>
                            <Input 
                              value={contract.productInfo?.quality || ""} 
                              onChange={e => setContract({
                                ...contract,
                                productInfo: {
                                  ...contract.productInfo,
                                  quality: e.target.value
                                }
                              })}
                              placeholder="Enter quality"
                            />
                          </div>
                          <div className="flex flex-col gap-2">
                            <span className="font-medium">Option</span>
                            <Select value={contract.productInfo?.qualityOption || "Buyer"} onValueChange={val => setContract({ ...contract, productInfo: { ...contract.productInfo, qualityOption: val } })}>
                              <SelectTrigger>
                                <SelectValue />
                              </SelectTrigger>
                              <SelectContent>
                                <SelectItem value="Seller">Seller</SelectItem>
                                <SelectItem value="Buyer">Buyer</SelectItem>
                              </SelectContent>
                            </Select>
                          </div>
                          <div className="flex flex-col gap-2">
                            <span className="font-medium">Final at</span>
                            <Select value={contract.productInfo?.qualityFinalAt || "Discharge"} onValueChange={val => setContract({ ...contract, productInfo: { ...contract.productInfo, qualityFinalAt: val } })}>
                              <SelectTrigger>
                                <SelectValue />
                              </SelectTrigger>
                              <SelectContent>
                                <SelectItem value="Loading">Loading</SelectItem>
                                <SelectItem value="Discharge">Discharge</SelectItem>
                              </SelectContent>
                            </Select>
                          </div>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                </TabsContent>

                <TabsContent 
                  value="delivery" 
                  className="px-4 lg:px-6"
                  style={{ display: isMobile && currentTab !== "delivery" ? "none" : "block" }}
                >
                  <Card>
                    <CardHeader>
                      <CardTitle className="flex items-center gap-2">
                        <Scale className="h-5 w-5" />
                        {t("bizz.deliveryperiod")}
                      </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">Start</span>
                          <Popover>
                            <PopoverTrigger asChild>
                              <Button
                                variant={"outline"}
                                className={cn(
                                  "w-full justify-start text-left font-normal",
                                  !contract.productInfo?.deliveryStart && "text-muted-foreground"
                                )}
                              >
                                <CalendarIcon className="mr-2 h-4 w-4" />
                                {contract.productInfo?.deliveryStart ? format(new Date(contract.productInfo.deliveryStart), "dd/MM/yyyy") : format(new Date(), "dd/MM/yyyy")}
                              </Button>
                            </PopoverTrigger>
                            <PopoverContent className="w-auto p-0">
                              <Calendar
                                mode="single"
                                selected={contract.productInfo?.deliveryStart ? new Date(contract.productInfo.deliveryStart) : new Date()}
                                onSelect={(date) => setContract({ 
                                  ...contract, 
                                  productInfo: { 
                                    ...contract.productInfo, 
                                    deliveryStart: date?.toISOString() 
                                  } 
                                })}
                                initialFocus
                              />
                            </PopoverContent>
                          </Popover>
                        </div>
                        <div className="flex flex-col gap-2">
                          <span className="font-medium">End</span>
                          <Popover>
                            <PopoverTrigger asChild>
                              <Button
                                variant={"outline"}
                                className={cn(
                                  "w-full justify-start text-left font-normal",
                                  !contract.productInfo?.deliveryEnd && "text-muted-foreground"
                                )}
                              >
                                <CalendarIcon className="mr-2 h-4 w-4" />
                                {contract.productInfo?.deliveryEnd ? format(new Date(contract.productInfo.deliveryEnd), "dd/MM/yyyy") : "Pick a date"}
                              </Button>
                            </PopoverTrigger>
                            <PopoverContent className="w-auto p-0">
                              <Calendar
                                mode="single"
                                selected={contract.productInfo?.deliveryEnd ? new Date(contract.productInfo.deliveryEnd) : undefined}
                                onSelect={(date) => setContract({ 
                                  ...contract, 
                                  productInfo: { 
                                    ...contract.productInfo, 
                                    deliveryEnd: date?.toISOString() 
                                  } 
                                })}
                                initialFocus
                              />
                            </PopoverContent>
                          </Popover>
                        </div>
                        <div className="flex flex-col gap-2">
                          <span className="font-medium">Option</span>
                          <Select value={contract.productInfo?.deliveryOption || ""} onValueChange={val => setContract({ ...contract, productInfo: { ...contract.productInfo, deliveryOption: val } })} disabled={!!contract.delivery?.parity}>
                            <SelectTrigger>
                              <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                              {contract.productInfo?.deliveryOption === "S/B" ? (
                                <>
                                  <SelectItem value="Seller">S</SelectItem>
                                  <SelectItem value="Buyer">B</SelectItem>
                                </>
                              ) : (
                                <SelectItem value={contract.productInfo?.deliveryOption === "Seller" ? "Seller" : "Buyer"}>
                                  {contract.productInfo?.deliveryOption === "Seller" ? "S" : "B"}
                                </SelectItem>
                              )}
                            </SelectContent>
                          </Select>
                        </div>
                        <div className="flex flex-col gap-2">
                          <span className="font-medium">Extension</span>
                          <Select value={contract.productInfo?.deliveryExtension ? "Yes" : "No"} onValueChange={val => setContract({ ...contract, productInfo: { ...contract.productInfo, deliveryExtension: val === "Yes" } })}>
                            <SelectTrigger className="w-full">
                              <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="Yes">Yes</SelectItem>
                              <SelectItem value="No">No</SelectItem>
                            </SelectContent>
                          </Select>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                </TabsContent>

                <TabsContent 
                  value="price" 
                  className="px-4 lg:px-6"
                  style={{ display: isMobile && currentTab !== "price" ? "none" : "block" }}
                >
                  <Card>
                    <CardHeader>
                      <CardTitle className="flex items-center gap-2">
                        <DollarIcon className="h-5 w-5" />
                        {t("bizz.price")}
                      </CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-4">
                      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
                      <div className="flex flex-col gap-2">
                          <span className="font-medium">Price Type</span>
                          <Select 
                            value={contract.financialInfo?.priceType || "Fixed"}
                            onValueChange={val => setContract({ 
                              ...contract, 
                              financialInfo: { 
                                ...contract.financialInfo, 
                                priceType: val 
                              } 
                            })}
                          >
                            <SelectTrigger className="w-full">
                              <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="Fixed">Fixed</SelectItem>
                              <SelectItem value="MATIF">MATIF</SelectItem>
                              <SelectItem value="Carry">Carry to</SelectItem>
                            </SelectContent>
                          </Select>
                        </div>
                        <div className="flex flex-col gap-2">
                          <span className="font-medium">{t("bizz.price")}</span>
                          <div className="flex gap-2">
                            <Input value={contract.financialInfo?.pricePerMt || " "} onChange={e => setContract({ ...contract, financialInfo: { ...contract.financialInfo, pricePerMt: e.target.value } })} className="w-1/2" />
                            <Select value={contract.financialInfo?.priceCurrency || "EUR"} onValueChange={val => setContract({ ...contract, financialInfo: { ...contract.financialInfo, priceCurrency: val } })}>
                              <SelectTrigger className="w-full">
                                <SelectValue />
                              </SelectTrigger>
                              <SelectContent>
                                <SelectItem value="EUR">EUR/to</SelectItem>
                                <SelectItem value="USD">USD/to</SelectItem>
                                <SelectItem value="RON">RON/to</SelectItem>
                              </SelectContent>
                            </Select>
                          </div>
                        </div>
                        
                      </div>
                      {contract.financialInfo?.priceType === "Fixed" && (
                        <div className="space-y-4">
                          <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
                            <div className="flex flex-col gap-2">
                              <span className="font-medium">Spread1</span>
                              <div className="flex gap-2">
                                <Input 
                                  value={contract.financialInfo?.spread1 || ""} 
                                  onChange={e => {
                                    const basePrice = Number(contract.financialInfo?.pricePerMt || 0);
                                    const spread1 = Number(e.target.value || 0);
                                    const spread2 = Number(contract.financialInfo?.spread2 || 0);
                                    const calculated = {
                                      price1: basePrice.toString(),
                                      price2: spread1 ? (basePrice - spread1).toString() : "",
                                      price3: spread2 ? (basePrice - spread2).toString() : ""
                                    };
                                    setContract({ 
                                      ...contract, 
                                      financialInfo: { 
                                        ...contract.financialInfo, 
                                        spread1: e.target.value
                                      },
                                      calculated
                                    });
                                  }} 
                                  className="" 
                                />
                                
                              </div>
                            </div>
                            <div className="flex flex-col gap-2">
                              <span className="font-medium">Spread2</span>
                              <div className="flex gap-2">
                                <Input 
                                  value={contract.financialInfo?.spread2 || ""} 
                                  onChange={e => {
                                    const basePrice = Number(contract.financialInfo?.pricePerMt || 0);
                                    const spread1 = Number(contract.financialInfo?.spread1 || 0);
                                    const spread2 = Number(e.target.value || 0);
                                    const calculated = {
                                      price1: basePrice.toString(),
                                      price2: spread1 ? (basePrice - spread1).toString() : "",
                                      price3: spread2 ? (basePrice - spread2).toString() : ""
                                    };
                                    setContract({ 
                                      ...contract, 
                                      financialInfo: { 
                                        ...contract.financialInfo, 
                                        spread2: e.target.value
                                      },
                                      calculated
                                    });
                                  }} 
                                  className="" 
                                />
                               
                              </div>
                            </div>
                          </div>
                          <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 mt-4">
                            {contract.financialInfo?.spread1 && (
                              <div className="flex flex-col gap-2">
                                <span className="font-medium">Price1 (Base Price - Spread1)</span>
                                <div className="flex gap-2">
                                  <Input value={contract.calculated?.price2 || ""} readOnly className="" />
                                </div>
                              </div>
                            )}
                            {contract.financialInfo?.spread2 && (
                              <div className="flex flex-col gap-2">
                                <span className="font-medium">Price2 (Base Price - Spread2)</span>
                                <div className="flex gap-2">
                                  <Input value={contract.calculated?.price3 || ""} readOnly className="" />
                                </div>
                              </div>
                            )}
                          </div>
                        </div>
                      )}
                      {contract.financialInfo?.priceType === "MATIF" && (
                        <div className="space-y-4">
                          <div className="flex flex-col gap-2">
                            <span className="font-medium">Matif Euronext Exchange</span>
                            <Select 
                              value={contract.financialInfo?.matifExchange || "march-25"} 
                              onValueChange={val => setContract({ 
                                ...contract, 
                                financialInfo: { 
                                  ...contract.financialInfo, 
                                  matifExchange: val 
                                } 
                              })}
                            >
                              <SelectTrigger className="w-full">
                                <SelectValue />
                              </SelectTrigger>
                              <SelectContent>
                                <SelectItem value="march-25">March 2025</SelectItem>
                                <SelectItem value="september-25">September 2025</SelectItem>
                                <SelectItem value="december-25">December 2025</SelectItem>
                                <SelectItem value="march-26">March 2026</SelectItem>
                              </SelectContent>
                            </Select>
                          </div>
                          <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
                            <div className="flex flex-col gap-2">
                              <span className="font-medium">Matif Price</span>
                              <div className="flex gap-2">
                                <Input 
                                  value={contract.financialInfo?.matifPrice || "29.50"} 
                                  onChange={e => setContract({ 
                                    ...contract, 
                                    financialInfo: { 
                                      ...contract.financialInfo, 
                                      matifPrice: e.target.value 
                                    } 
                                  })} 
                                  className="w-1/2" 
                                />
                                <Select 
                                  value={contract.financialInfo?.matifPriceCurrency || "EUR"} 
                                  onValueChange={val => setContract({ 
                                    ...contract, 
                                    financialInfo: { 
                                      ...contract.financialInfo, 
                                      matifPriceCurrency: val 
                                    } 
                                  })}
                                >
                                  <SelectTrigger className="w-full">
                                    <SelectValue />
                                  </SelectTrigger>
                                  <SelectContent>
                                    <SelectItem value="EUR">EUR</SelectItem>
                                    <SelectItem value="USD">USD</SelectItem>
                                  </SelectContent>
                                </Select>
                              </div>
                            </div>
                            <div className="flex flex-col gap-2">
                              <span className="font-medium">Provisional Price</span>
                              <div className="flex gap-2">
                                <Input 
                                  value={contract.financialInfo?.provisionalPrice || "187.00"} 
                                  onChange={e => setContract({ 
                                    ...contract, 
                                    financialInfo: { 
                                      ...contract.financialInfo, 
                                      provisionalPrice: e.target.value 
                                    } 
                                  })} 
                                  className="w-1/2" 
                                />
                                <Select 
                                  value={contract.financialInfo?.provisionalPriceCurrency || "EUR"} 
                                  onValueChange={val => setContract({ 
                                    ...contract, 
                                    financialInfo: { 
                                      ...contract.financialInfo, 
                                      provisionalPriceCurrency: val 
                                    } 
                                  })}
                                >
                                  <SelectTrigger className="w-full">
                                    <SelectValue />
                                  </SelectTrigger>
                                  <SelectContent>
                                    <SelectItem value="EUR">EUR</SelectItem>
                                    <SelectItem value="USD">USD</SelectItem>
                                  </SelectContent>
                                </Select>
                              </div>
                            </div>
                            <div className="flex flex-col gap-2">
                              <span className="font-medium">Collateral</span>
                              <div className="flex gap-2">
                                <Input 
                                  value={contract.financialInfo?.collateral || "170.40"} 
                                  onChange={e => setContract({ 
                                    ...contract, 
                                    financialInfo: { 
                                      ...contract.financialInfo, 
                                      collateral: e.target.value 
                                    } 
                                  })} 
                                  className="w-1/2" 
                                />
                                <Select 
                                  value={contract.financialInfo?.collateralCurrency || "EUR"} 
                                  onValueChange={val => setContract({ 
                                    ...contract, 
                                    financialInfo: { 
                                      ...contract.financialInfo, 
                                      collateralCurrency: val 
                                    } 
                                  })}
                                >
                                  <SelectTrigger className="w-full">
                                    <SelectValue />
                                  </SelectTrigger>
                                  <SelectContent>
                                    <SelectItem value="EUR">EUR</SelectItem>
                                    <SelectItem value="USD">USD</SelectItem>
                                  </SelectContent>
                                </Select>
                              </div>
                            </div>
                            <div className="flex flex-col gap-2">
                              <span className="font-medium">Deposit</span>
                              <div className="flex gap-2">
                                <Input 
                                  value={contract.financialInfo?.deposit || "20"} 
                                  onChange={e => setContract({ 
                                    ...contract, 
                                    financialInfo: { 
                                      ...contract.financialInfo, 
                                      deposit: e.target.value 
                                    } 
                                  })} 
                                  className="w-1/2" 
                                />
                                <Select 
                                  value={contract.financialInfo?.depositCurrency || "EUR"} 
                                  onValueChange={val => setContract({ 
                                    ...contract, 
                                    financialInfo: { 
                                      ...contract.financialInfo, 
                                      depositCurrency: val 
                                    } 
                                  })}
                                >
                                  <SelectTrigger className="w-full">
                                    <SelectValue />
                                  </SelectTrigger>
                                  <SelectContent>
                                    <SelectItem value="EUR">EUR</SelectItem>
                                    <SelectItem value="USD">USD</SelectItem>
                                  </SelectContent>
                                </Select>
                              </div>
                            </div>
                          </div>
                          <div className="flex flex-col gap-2">
                            <span className="font-medium">Additional Mentions</span>
                            <textarea 
                              value={contract.financialInfo?.priceAdditionalMentions || ""} 
                              onChange={e => setContract({ 
                                ...contract, 
                                financialInfo: { 
                                  ...contract.financialInfo, 
                                  priceAdditionalMentions: e.target.value 
                                } 
                              })} 
                              className="border rounded p-2 min-h-[80px] w-full"
                            />
                          </div>
                        </div>
                      )}
                      {contract.financialInfo?.priceType === "Carry" && (
                        <div className="space-y-4">
                          <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
                            <div className="flex flex-col gap-2">
                              <span className="font-medium">Price</span>
                              <div className="flex gap-2">
                                <Input 
                                  value={contract.financialInfo?.carryPrice1 || "187"} 
                                  onChange={e => setContract({ 
                                    ...contract, 
                                    financialInfo: { 
                                      ...contract.financialInfo, 
                                      carryPrice1: e.target.value 
                                    } 
                                  })} 
                                  className="w-1/2" 
                                />
                                <Select 
                                  value={contract.financialInfo?.carryPrice1Currency || "EUR"} 
                                  onValueChange={val => setContract({ 
                                    ...contract, 
                                    financialInfo: { 
                                      ...contract.financialInfo, 
                                      carryPrice1Currency: val 
                                    } 
                                  })}
                                >
                                  <SelectTrigger className="w-full">
                                    <SelectValue />
                                  </SelectTrigger>
                                  <SelectContent>
                                    <SelectItem value="EUR">EUR/to</SelectItem>
                                    <SelectItem value="USD">USD/to</SelectItem>
                                  </SelectContent>
                                </Select>
                              </div>
                            </div>
                            <div className="flex flex-col gap-2">
                              <span className="font-medium">Carry</span>
                              <div className="flex gap-2">
                                <Input 
                                  value={contract.financialInfo?.carry || "2"} 
                                  onChange={e => setContract({ 
                                    ...contract, 
                                    financialInfo: { 
                                      ...contract.financialInfo, 
                                      carry: e.target.value 
                                    } 
                                  })} 
                                  className="w-1/2" 
                                />
                                <Select 
                                  value={contract.financialInfo?.carryCurrency || "EUR"} 
                                  onValueChange={val => setContract({ 
                                    ...contract, 
                                    financialInfo: { 
                                      ...contract.financialInfo, 
                                      carryCurrency: val 
                                    } 
                                  })}
                                >
                                  <SelectTrigger className="w-full">
                                    <SelectValue />
                                  </SelectTrigger>
                                  <SelectContent>
                                    <SelectItem value="EUR">EUR/to</SelectItem>
                                    <SelectItem value="USD">USD/to</SelectItem>
                                  </SelectContent>
                                </Select>
                              </div>
                            </div>
                          </div>
                        </div>
                      )}
                    </CardContent>
                  </Card>
                </TabsContent>

                <TabsContent 
                  value="payment" 
                  className="px-4 lg:px-6"
                  style={{ display: isMobile && currentTab !== "payment" ? "none" : "block" }}
                >
                  <Card>
                    <CardHeader>
                      <CardTitle className="flex items-center gap-2">
                        <DollarIcon className="h-5 w-5" />
                        {t("bizz.paymentterms")}
                      </CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-4">
                      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
                        <div className="flex flex-col gap-2">
                          <span className="font-medium">Payment Type</span>
                          <ComboboxFull 
                            items={paymentTypeOptions}
                            value={contract.payment?.type || ""}
                            onValueChange={(value) => {
                              const newPaymentType = value as keyof typeof paymentDetailsMap;
                              setContract({
                                ...contract,
                                payment: {
                                  ...contract.payment,
                                  type: newPaymentType,
                                  terms: "", // Reset terms when payment type changes
                                  moment: "", // Reset moment
                                  invoice: "" // Reset invoice
                                }
                              });
                            }}
                            placeholder="Select payment type"
                            emptyText="No payment type options"
                          />
                        </div>

                        <div className="flex flex-col gap-2">
                          <span className="font-medium">Payment Terms</span>
                          <ComboboxFull
                            items={contract.payment?.type ? paymentTermsOptions[contract.payment.type as keyof typeof paymentTermsOptions] || [] : []}
                            value={contract.payment?.terms || ""}
                            onValueChange={(value) => {
                              const selectedPaymentType = contract.payment?.type as keyof typeof paymentDetailsMap;
                              const selectedTerm = value as keyof typeof paymentDetailsMap[typeof selectedPaymentType];
                              const termsDetails = paymentDetailsMap[selectedPaymentType]?.[selectedTerm] || [];
                              
                              const uniqueMoments = Array.from(new Set(termsDetails.map(detail => detail.moment)));
                              const defaultMoment = uniqueMoments.length === 1 ? uniqueMoments[0] : "";

                              const invoicesForDefaultMoment = termsDetails.filter(detail => detail.moment === defaultMoment);
                              const uniqueInvoices = Array.from(new Set(invoicesForDefaultMoment.map(detail => detail.invoice)));
                              const defaultInvoice = uniqueInvoices.length === 1 ? uniqueInvoices[0] : "";

                              setContract({
                                ...contract,
                                payment: {
                                  ...contract.payment,
                                  terms: value,
                                  moment: defaultMoment,
                                  invoice: defaultInvoice
                                }
                              });
                            }}
                            placeholder="Select payment terms"
                            emptyText="No payment terms available"
                            disabled={!contract.payment?.type}
                          />
                        </div>
                        <div>
                          <span className="font-medium">Payment Moment</span>
                          <Select
                            value={contract.payment?.moment || ""}
                            onValueChange={(val) => {
                              const selectedPaymentType = contract.payment?.type as keyof typeof paymentDetailsMap;
                              const selectedTerm = contract.payment?.terms as keyof typeof paymentDetailsMap[typeof selectedPaymentType];
                              const termsDetails = paymentDetailsMap[selectedPaymentType]?.[selectedTerm] || [];
                              const invoicesForSelectedMoment = termsDetails.filter(detail => detail.moment === val);
                              const uniqueInvoices = Array.from(new Set(invoicesForSelectedMoment.map(detail => detail.invoice)));
                              const defaultInvoice = uniqueInvoices.length === 1 ? uniqueInvoices[0] : "";

                              setContract({
                                ...contract,
                                payment: {
                                  ...contract.payment,
                                  moment: val,
                                  invoice: defaultInvoice
                                }
                              });
                            }}
                            disabled={!(contract.payment?.type && contract.payment?.terms) || (Array.from(new Set((paymentDetailsMap[contract.payment.type as keyof typeof paymentDetailsMap]?.[contract.payment.terms as keyof typeof paymentDetailsMap[typeof contract.payment.type]] || []).map(detail => detail.moment))).length <= 1)}
                          >
                            <SelectTrigger className="w-full">
                              <SelectValue placeholder="Select payment moment" />
                            </SelectTrigger>
                            <SelectContent>
                              {Array.from(new Set((paymentDetailsMap[contract.payment.type as keyof typeof paymentDetailsMap]?.[contract.payment.terms as keyof typeof paymentDetailsMap[typeof contract.payment.type]] || []).map(option => option.moment))).map(moment => (
                                <SelectItem key={moment} value={moment}>
                                  {moment}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        </div>
                        <div className="flex flex-col gap-2">
                          <span className="font-medium">Payment Invoice</span>
                          <ComboboxFull
                            items={Array.from(new Set((paymentDetailsMap[contract.payment.type as keyof typeof paymentDetailsMap]?.[contract.payment.terms as keyof typeof paymentDetailsMap[typeof contract.payment.type]] || []).filter(detail => !contract.payment?.moment || detail.moment === contract.payment.moment).map(option => option.invoice))).map(invoice => ({ value: invoice, label: invoice }))}
                            value={contract.payment?.invoice || ""}
                            onValueChange={(value) => {
                              setContract({
                                ...contract,
                                payment: {
                                  ...contract.payment,
                                  invoice: value
                                }
                              });
                            }}
                            placeholder="Select invoice type"
                            emptyText="No invoice options"
                            disabled={!(contract.payment?.type && contract.payment?.terms && contract.payment?.moment) || (Array.from(new Set((paymentDetailsMap[contract.payment.type as keyof typeof paymentDetailsMap]?.[contract.payment.terms as keyof typeof paymentDetailsMap[typeof contract.payment.type]] || []).filter(detail => !contract.payment?.moment || detail.moment === contract.payment.moment).map(option => option.invoice))).length <= 1)}
                          />
                        </div>
                        <div className="flex flex-col gap-2">
                          <span className="font-medium">Guarantees</span>
                          <Select
                            value={contract.productInfo?.guarantees === false ? "No" : "Yes"}
                            onValueChange={val => setContract({
                              ...contract,
                              productInfo: {
                                ...contract.productInfo,
                                guarantees: val === "Yes"
                              }
                            })}
                          >
                            <SelectTrigger className="w-full">
                              <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="No">No</SelectItem>
                              <SelectItem value="Yes">Yes</SelectItem>
                            </SelectContent>
                          </Select>
                        </div>
                      </div>

                      {contract.productInfo?.guarantees && (
                        <div className="border rounded p-4 mt-4 bg-muted/100">
                          <div className="space-y-4">
                            <div className="flex flex-col gap-2">
                              <span className="font-medium">Guarantee Type</span>
                              <Select 
                                value={contract.productInfo?.guaranteeType || ""}
                                onValueChange={val => setContract({ 
                                  ...contract, 
                                  productInfo: { 
                                    ...contract.productInfo, 
                                    guaranteeType: val 
                                  } 
                                })}
                              >
                                <SelectTrigger className="w-full">
                                  <SelectValue placeholder="Select guarantee type" />
                                </SelectTrigger>
                                <SelectContent>
                                  <SelectItem value="BO - Alb">BO - Alb</SelectItem>
                                  <SelectItem value="BO - Alb Avalizat">BO - Alb Avalizat</SelectItem>
                                  <SelectItem value="BO - Completat">BO - Completat</SelectItem>
                                  <SelectItem value="CEC">CEC</SelectItem>
                                </SelectContent>
                              </Select>
                            </div>
                            <div className="flex flex-col gap-2">
                              <span className="font-medium">Guarantee Series</span>
                              <Input 
                                value={contract.productInfo?.guaranteeTitle || ""} 
                                onChange={e => setContract({ 
                                  ...contract, 
                                  productInfo: { 
                                    ...contract.productInfo, 
                                    guaranteeTitle: e.target.value 
                                  } 
                                })}
                                placeholder="Enter guarantee title"
                              />
                            </div>
                            <div className="flex flex-col gap-2">
                              <span className="font-medium">Guarantee Status</span>
                              <Select 
                                value={contract.productInfo?.guaranteeStatus || ""}
                                onValueChange={val => setContract({ 
                                  ...contract, 
                                  productInfo: { 
                                    ...contract.productInfo, 
                                    guaranteeStatus: val 
                                  } 
                                })}
                              >
                                <SelectTrigger className="w-full">
                                  <SelectValue placeholder="Select guarantee status" />
                                </SelectTrigger>
                                <SelectContent>
                                  <SelectItem value="not needed">Not needed</SelectItem>
                                  <SelectItem value="requested">Requested</SelectItem>
                                  <SelectItem value="scanned by email">Scanned by email</SelectItem>
                                  <SelectItem value="original at broker">Original at broker</SelectItem>
                                  <SelectItem value="original at counterparty">Original at counterparty</SelectItem>
                                </SelectContent>
                              </Select>
                            </div>
                          </div>
                        </div>
                      )}
                    </CardContent>
                  </Card>
                </TabsContent>

                <TabsContent 
                  value="delivery-condition" 
                  className="px-4 lg:px-6"
                  style={{ display: isMobile && currentTab !== "delivery-condition" ? "none" : "block" }}
                >
                  <Card>
                    <CardHeader>
                      <CardTitle className="flex items-center gap-2">
                        <Scale className="h-5 w-5" />
                        {t("bizz.deliverycondition")}
                      </CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-4">
                      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
                        <div className="flex flex-col gap-2">
                          <span className="font-medium">Incoterms</span>
                          <ComboboxFull 
                            items={parityOptions}
                            value={contract.delivery?.parity || ""}
                            onValueChange={(value) => {
                              const selectedIncoterm = incotermOptionsMapping[value];
                              if (selectedIncoterm) {
                                setContract({ 
                                  ...contract, 
                                  delivery: { 
                                    ...contract.delivery, 
                                    parity: value 
                                  },
                                  productInfo: {
                                    ...contract.productInfo,
                                    deliveryOption: selectedIncoterm.deliveryPlace, // S, B, or S/B
                                    deliveryExtension: selectedIncoterm.deliveryPeriod // S, B, S/S, or S/B
                                  }
                                });
                              } else {
                                setContract({ 
                                  ...contract, 
                                  delivery: { 
                                    ...contract.delivery, 
                                    parity: value,
                                    // Clear values if Incoterm is unselected
                                    locations: [], // Clear locations
                                    transports: [], // Clear transports
                                    conditions: ""
                                  },
                                  productInfo: {
                                    ...contract.productInfo,
                                    deliveryOption: "",
                                    deliveryExtension: ""
                                  }
                                });
                              }
                            }}
                            placeholder="Select incoterms"
                            emptyText="No incoterms options"
                          />
                        </div>
                        <div className="flex flex-col gap-2">
                          <span className="font-medium">Location</span>
                          {contract.delivery.locations.length === 0 && (
                             <Button 
                               variant="secondary" 
                               size="sm" 
                               onClick={() => setContract({
                                 ...contract,
                                 delivery: { ...contract.delivery, locations: [...contract.delivery.locations, { name: "", value: "", currency: contract.financialInfo?.priceCurrency || "EUR" }] }
                               })}
                               className="w-full bg-black text-white hover:bg-gray-800"
                             >
                               + Add Location
                             </Button>
                          )}
                          {contract.delivery.locations.map((location: any, index: number) => (
                            <div key={index} className="flex items-center gap-2 w-full">
                              <div className="flex-grow">
                                <ComboboxFull 
                                  items={locationOptions}
                                  value={location.name || ""}
                                  onValueChange={(value) => {
                                    const updatedLocations = [...contract.delivery.locations];
                                    updatedLocations[index] = { ...updatedLocations[index], name: value };
                                    setContract({
                                      ...contract,
                                      delivery: { ...contract.delivery, locations: updatedLocations }
                                    });
                                  }}
                                  placeholder="Select location"
                                  emptyText="No location options"
                                />
                              </div>
                              <Input 
                                value={location.value || ""}
                                onChange={e => {
                                  const updatedLocations = [...contract.delivery.locations];
                                  updatedLocations[index] = { ...updatedLocations[index], value: e.target.value };
                                  setContract({ ...contract, delivery: { ...contract.delivery, locations: updatedLocations } });
                                }}
                                className="w-[60px]"
                                placeholder="Value"
                              />
                              <Input 
                                value={location.currency || contract.financialInfo?.priceCurrency || "EUR"}
                                readOnly
                                className="w-[50px] bg-muted"
                              />
                              {contract.delivery.locations.length > 1 && (
                                <Button 
                                  variant="outline" 
                                  size="icon" 
                                  onClick={() => {
                                    const updatedLocations = contract.delivery.locations.filter((_: any, i: number) => i !== index);
                                    setContract({ ...contract, delivery: { ...contract.delivery, locations: updatedLocations } });
                                  }}
                                  className="shrink-0 h-8 w-8"
                                >
                                  <IconCircleX className="h-4 w-4" />
                                </Button>
                              )}
                              {index === contract.delivery.locations.length - 1 && (
                                <Button 
                                  variant="secondary" 
                                  size="icon" 
                                  onClick={() => setContract({
                                    ...contract,
                                    delivery: { ...contract.delivery, locations: [...contract.delivery.locations, { name: "", value: "", currency: contract.financialInfo?.priceCurrency || "EUR" }] }
                                  })}
                                  className="shrink-0 bg-black text-white hover:bg-gray-800 h-8 w-8"
                                >
                                  +
                                </Button>
                              )}
                            </div>
                          ))}
                        </div>
                        <div className="flex flex-col gap-2">
                          <span className="font-medium">Means of Transport</span>
                          <div className="flex flex-wrap items-end gap-2">
                          <ComboboxFull 
                            items={transportOptions}
                            value={contract.delivery?.transport || ""}
                            onValueChange={(value) => {
                              setContract({ 
                                ...contract, 
                                delivery: { 
                                  ...contract.delivery, 
                                  transport: value 
                                } 
                              });
                            }}
                            placeholder="Select means of transport"
                            emptyText="No transport options"
                          />
                          </div>
                        </div>
                        <div className="flex flex-col gap-2">
                          <span className="font-medium">Delivery Option</span>
                          <Select value={contract.productInfo?.deliveryOption ? "Buyer" : "Seller"} onValueChange={val => setContract({ ...contract, productInfo: { ...contract.productInfo, deliveryOption: val === "Buyer" } })}>
                            <SelectTrigger>
                              <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="Buyer">B</SelectItem>
                              <SelectItem value="Seller">S</SelectItem>
                            </SelectContent>
                          </Select>
                        </div>
                      </div>
                      <div className="flex flex-col gap-2 mt-2">
                        <span className="font-medium">Delivery Conditions</span>
                        <textarea
                          value={contract.delivery?.conditions || ""}
                          onChange={e => setContract({
                            ...contract,
                            delivery: {
                              ...contract.delivery,
                              conditions: e.target.value
                            }
                          })}
                          className="border rounded p-2 min-h-[80px] w-full"
                        />
                      </div>
                    </CardContent>
                  </Card>
                </TabsContent>

                <TabsContent 
                  value="notes" 
                  className="px-4 lg:px-6"
                  style={{ display: isMobile && currentTab !== "notes" ? "none" : "block" }}
                >
                  <Card>
                    <CardHeader>
                      <CardTitle className="flex items-center gap-2">
                        <IconPackage className="h-5 w-5" />
                        {t("bizz.notes")}
                      </CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-4">
                      <div className="flex flex-col gap-2">
                        <span className="font-medium">Buyer Notes</span>
                        <textarea 
                          value={companyNotes[selectedBuyerCompany]?.buyerNote || ""} 
                          onChange={e => {
                            setCompanyNotes(prev => ({
                              ...prev,
                              [selectedBuyerCompany]: {
                                ...prev[selectedBuyerCompany],
                                buyerNote: e.target.value
                              }
                            }));
                          }}
                          className="border rounded p-2 min-h-[80px] w-full"
                        />
                      </div>
                      <div className="flex flex-col gap-2">
                        <span className="font-medium">Seller Notes</span>
                        <textarea 
                          value={companyNotes[selectedCompany]?.sellerNote || ""} 
                          onChange={e => {
                            setCompanyNotes(prev => ({
                              ...prev,
                              [selectedCompany]: {
                                ...prev[selectedCompany],
                                sellerNote: e.target.value
                              }
                            }));
                          }}
                          className="border rounded p-2 min-h-[80px] w-full"
                        />
                      </div>
                      <div className="flex flex-col gap-2">
                        <span className="font-medium">Internal Notes</span>
                        <textarea 
                          value={contract.notes || ""} 
                          onChange={e => setContract({ ...contract, notes: e.target.value })} 
                          className="border rounded p-2 min-h-[80px] w-full"
                        />
                      </div>
                    </CardContent>
                  </Card>
                </TabsContent>
              </div>
            </Tabs>
          </div>
          <div className="flex justify-between px-4 lg:px-6 pb-2">
            {isMobile ? (
              <>
                <Button 
                  variant="outline" 
                  onClick={handlePrevious} 
                  disabled={currentTab === "general"}
                  className="flex-1 mx-1"
                >
                  Previous
                </Button>
                <Button 
                  variant="outline"
                  onClick={handleSave}
                  className="flex-1 mx-1"
                >
                  Save
                </Button>
                <Button 
                  onClick={handleSendClick}
                  className="flex-1 mx-1"
                >
                  Send
                </Button>
                <Button 
                  onClick={handleNext} 
                  disabled={currentTab === "notes"}
                  className="flex-1 mx-1"
                >
                  Next
                </Button>
              </>
            ) : (
              <div className="flex gap-2">
                <Button variant="outline" onClick={handleSave}>Save Draft</Button>
                <Button onClick={handleSendClick}>Send Bizz</Button>
              </div>
            )}
          </div>

          <Dialog open={showSendDialog} onOpenChange={setShowSendDialog}>
            <DialogContent>
              <DialogHeader>
                <DialogTitle>Send BizzConf</DialogTitle>
                <DialogDescription>
                  Select who should receive the BizzConf
                </DialogDescription>
              </DialogHeader>
              <div className="py-4">
                <Select value={selectedRecipientType} onValueChange={setSelectedRecipientType}>
                  <SelectTrigger>
                    <SelectValue placeholder="Select recipient" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="seller">S</SelectItem>
                    <SelectItem value="buyer">B</SelectItem>
                    <SelectItem value="both">S & B</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <DialogFooter>
                <Button variant="outline" onClick={() => setShowSendDialog(false)}>
                  Cancel
                </Button>
                <Button 
                  onClick={handleSend}
                  disabled={!selectedRecipientType}
                >
                  Send
                </Button>
              </DialogFooter>
            </DialogContent>
          </Dialog>
        </div>
      </SidebarInset>
    </SidebarProvider>
  )
} 