"use client"

import { useState, useEffect } from "react"
import { useTranslation } from "react-i18next"
import { useRouter } from "next/navigation"
import { AppSidebar } from "@/components/app-sidebar"
import { SiteHeader } from "@/components/site-header"
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Textarea } from "@/components/ui/textarea"
import { Globe, Percent, FileText, FileSignature, ClipboardCheck } from "lucide-react"
import {  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger, } from "@/components/ui/alert-dialog"
  import { BuildingIcon, DollarIcon } from "@/components/ui/icons"
  import { IconMessageLanguage, IconFileTypeDoc, IconSignature, IconHourglassEmpty } from "@tabler/icons-react"
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs"
import { Calendar } from "@/components/ui/calendar"
import { Combobox } from "@/components/combobox"
import { ComboboxFull } from "@/components/combobox-full"
import { format } from "date-fns"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { cn } from "@/lib/utils"
import { CalendarIcon } from "lucide-react"

interface NewContract {
  contractNumber: string;
  company: string;
  status: string;
  goods: string;
  quantity: number;
  contractType: string;
  startDate: string;
  endDate: string;
  price: number;
  currency: string;
  paymentTerms: string;
  deliveryTerms: string;
  personInCharge: string;
  department: string;
  notes: string;
  attachments: string[];
  relatedContracts: string[];
  contractDate: string;
  goodsFullDescription: string;
  qualityTerms: string;
  quantitymts: number;
  incoterms: string;
  deliveryPlace: string;
  pricePerMT: number;
  priceCurrency: string;
  basicInfo: {
    sellerCompany?: string;
    buyerCompany?: string;
    goodsCode?: string;
    cropYear?: string;
    origin?: string;
    buyerEmail?: string;
    sellerEmail?: string;
  };
  productInfo: {
    quantity?: string;
    unit?: string;
    toleranceType?: string;
    tolerance?: string;
    quantityOption?: string;
    finalAt?: string;
    quality?: string;
    qualityOption?: string;
    qualityFinalAt?: string;
    deliveryOption?: string;
    deliveryExtension?: boolean;
    guarantees?: boolean;
    guaranteeTitle?: string;
  };
  financialInfo: {
    priceType?: string;
    pricePerMt?: string;
    priceCurrency?: string;
    spread1?: string;
    spread1Currency?: string;
    spread3?: string;
    spread3Currency?: string;
    matifExchange?: string;
    matifPrice?: string;
    matifPriceCurrency?: string;
    provisionalPrice?: string;
    provisionalPriceCurrency?: string;
    collateral?: string;
    collateralCurrency?: string;
    deposit?: string;
    depositCurrency?: string;
    priceAdditionalMentions?: string;
    carryPrice1?: string;
    carryPrice1Currency?: string;
    carry?: string;
    carryCurrency?: string;
  };
  payment: {
    type?: string;
    moment?: boolean;
    invoice?: string;
  };
  delivery: {
    parity?: string;
    location?: string;
    transport?: string;
    conditions?: string;
  };
  carryOrSpreadPrice: string;
  paymentDays: string;
  deliveryDateFrom: string;
  deliveryDateTo: string;
  deliveryTermSBOption: string;
  otherTerms: string;
  externalContractNo: string;
  goodsFullDescriptionENG: string;
  qualityTermsENG: string;
  quantityToleranceENG: string;
  deliveryPlaceENG: string;
  priceCurrencyENG: string;
  carryOrSpreadPriceENG: string;
  paymentTermsENG: string;
  deliveryTermSBOptionENG: string;
  otherTermsENG: string;
  whoIsPayingCommission: string;
  sellerCommission: string;
  sellerCommissionCurrency: string;
  buyerCommission: string;
  buyerCommissionCurrency: string;
  contractDraft: string;
  addTypeLb: string;
  artTypeLb: string;
  sellerBrokerCode: string;
  buyerBrokerCode: string;
  initialQuantity: string;
  guaranteesBO: string;
  statusBO: string;
  sellerSigned: string;
  buyerSigned: string;
  brokerSigned: string;
  executedQuantity: string;
  remainingToBeExecuted: string;
  commissionInvoice: string;
  totalCommisionEURmt: string;
  totalValueCommissionEUR: string;
  sellerBrokerCommission: string;
  buyerBrokerCommission: string;
  contractCurrencyDate: string;
  sellerExchangeRate: string;
  buyerExchangeRate: string;
  defaultQTY: string;
  executionYear: string;
  selectedPic: string;
  contractSignedStatus: string;
  contractDateCheck: string;
}

const brokers = [
  {name: "BNK BROKERS S.R.L",
   code: "BRO"
  }, 
  {name: "BNK INTERNATIONAL S.R.L",
    code: "BNK"}
  ];

const companies = ["RODBUN GRUP S.A.", "RURAL GRAIN TRADING", "QUADRA COMMODITIES", "ARPREST S.R.L.", "BARCA ALEXANDRU"];
const statuses = ["Open", "Pending", "Closed"];
const goodsList = ["BARLEY", "RAPESEED", "WHEAT"];
const goodsCode = ["BLY", "RPS", "MW"]
const cropYears = ["2022", "2023", "2024"];
const priceCurrencies = ["USD", "EUR", "RON"];
const paymentDaysList = ["7", "14", "30", "60"];
const whoIsPayingList = ["Seller", "Buyer"];
const picList = ["John Doe", "Jane Smith", "Alex Popescu"];

type FormValues = {
  broker: string;
  bank: string;
  code: string;
};

export default function NewContractPage() {
  const [lastContractNumber, setLastContractNumber] = useState<string>("0000");
  const [contract, setContract] = useState<NewContract>({
    contractNumber: "", // We'll set this after broker selection
    company: "",
    status: "Draft",
    goods: "",
    quantity: 0,
    contractType: "",
    startDate: "",
    endDate: "",
    price: 0,
    currency: "",
    paymentTerms: "",
    deliveryTerms: "",
    personInCharge: "",
    department: "",
    notes: "",
    attachments: [],
    relatedContracts: [],
    contractDate: "",
    goodsFullDescription: "",
    qualityTerms: "",
    quantitymts: 0,
    incoterms: "",
    deliveryPlace: "",
    pricePerMT: 0,
    priceCurrency: "",
    basicInfo: {
      sellerCompany: "",
      buyerCompany: "",
      goodsCode: "",
      cropYear: "",
      origin: "",
      buyerEmail: "",
      sellerEmail: "",
    },
    productInfo: {
      quantity: "",
      unit: "",
      toleranceType: "",
      tolerance: "",
      quantityOption: "",
      finalAt: "",
      quality: "",
      qualityOption: "",
      qualityFinalAt: "",
      deliveryOption: "",
      deliveryExtension: false,
      guarantees: false,
      guaranteeTitle: "",
    },
    financialInfo: {
      priceType: "",
      pricePerMt: "",
      priceCurrency: "",
      spread1: "",
      spread1Currency: "",
      spread3: "",
      spread3Currency: "",
      matifExchange: "",
      matifPrice: "",
      matifPriceCurrency: "",
      provisionalPrice: "",
      provisionalPriceCurrency: "",
      collateral: "",
      collateralCurrency: "",
      deposit: "",
      depositCurrency: "",
      priceAdditionalMentions: "",
      carryPrice1: "",
      carryPrice1Currency: "",
      carry: "",
      carryCurrency: "",
    },
    payment: {
      type: "",
      moment: false,
      invoice: "",
    },
    delivery: {
      parity: "",
      location: "",
      transport: "",
      conditions: "",
    },
    carryOrSpreadPrice: "",
    paymentDays: "",
    deliveryDateFrom: "",
    deliveryDateTo: "",
    deliveryTermSBOption: "",
    otherTerms: "",
    externalContractNo: "",
    goodsFullDescriptionENG: "",
    qualityTermsENG: "",
    quantityToleranceENG: "",
    deliveryPlaceENG: "",
    priceCurrencyENG: "",
    carryOrSpreadPriceENG: "",
    paymentTermsENG: "",
    deliveryTermSBOptionENG: "",
    otherTermsENG: "",
    whoIsPayingCommission: "",
    sellerCommission: "",
    sellerCommissionCurrency: "",
    buyerCommission: "",
    buyerCommissionCurrency: "",
    contractDraft: "",
    addTypeLb: "",
    artTypeLb: "",
    sellerBrokerCode: "",
    buyerBrokerCode: "",
    initialQuantity: "",
    guaranteesBO: "",
    statusBO: "",
    sellerSigned: "",
    buyerSigned: "",
    brokerSigned: "",
    executedQuantity: "",
    remainingToBeExecuted: "",
    commissionInvoice: "",
    totalCommisionEURmt: "",
    totalValueCommissionEUR: "",
    sellerBrokerCommission: "",
    buyerBrokerCommission: "",
    contractCurrencyDate: "",
    sellerExchangeRate: "",
    buyerExchangeRate: "",
    defaultQTY: "",
    executionYear: "",
    selectedPic: "",
    contractSignedStatus: "",
    contractDateCheck: "",
  });

  const { t } = useTranslation()
  const router = useRouter()

  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [selectedCompany, setSelectedCompany] = useState("");

  const [selectedGood, setSelectedGood] = useState("");
  const [selectedGoodCode, setSelectedGoodCode] = useState("");
  const [selectedPic, setSelectedPic] = useState("");
  const [contractNumber, setContractNumber] = useState<string>("");
  const [dialogOpen, setDialogOpen] = useState(false);
  const [selectedBroker, setSelectedBroker] = useState<string>("");
  const [contractCode, setContractCode] = useState<string>("");

  const currentBroker = brokers.find((b) => b.name === selectedBroker);

  const [isMobile, setIsMobile] = useState(false)
  const [isMobileCheckComplete, setIsMobileCheckComplete] = useState(false)
  const [loading, setLoading] = useState(false)
  const [currentTab, setCurrentTab] = useState("contract-details")
  const [locationOptions, setLocationOptions] = 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 [externalContractOptions, setExternalContractOptions] = useState<{ value: string; label: string }[]>([]);
  const [companies, setCompanies] = useState<string[]>([]);
  const [productCode, setProductCode] = useState<string[]>([]);
  const [cropYear, setCropYear] = useState<string[]>([]);
  const [origin, setOrigin] = useState<string[]>([]);
  const [selectedBuyerCompany, setSelectedBuyerCompany] = useState<string>("")
  const [selectedProductCode, setSelectedProductCode] = useState<string>("")
  const [selectedCropYear, setSelectedCropYear] = useState<string>("")
  const [selectedOrigin, setSelectedOrigin] = useState<string>("")
  const [showCompanyDialog, setShowCompanyDialog] = useState(false)
  const [newCompanyName, setNewCompanyName] = useState("")
  const [isCreatingCompany, setIsCreatingCompany] = useState(false)

  const [whoIsPayingOptions] = useState([
    { value: "S", label: "S" },
    { value: "B", label: "B" },
    { value: "S+B", label: "S + B" }
  ]);

  const [currencyOptions] = useState([
    { value: "RON", label: "RON" },
    { value: "EUR", label: "EUR" },
    { value: "USD", label: "USD" }
  ]);

  const [boStatusOptions] = useState([
    { value: "Semnat", label: "Semnat" },
    { value: "Copy", label: "Copy" }
  ]);

  const [signedOptions] = useState([
    { value: "Semnat", label: "Semnat" },
    { value: "Copy", label: "Copy" }
  ]);

  const [toleranceTypeOptions] = useState([
    { value: "percentage", label: "%" },
    { value: "tonnage", label: "to" },
    { value: "min/max", label: "min/max"}
  ]);

  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 [qualityOptions, setQualityOptions] = useState<Array<{ value: string; label: string }>>([]);

  const [quantityOptions] = useState([
    { value: "1000", label: "1000" },
    { value: "1500", label: "1500" },
    { value: "3000", label: "3000" }
  ]);

  const [priceTypeOptions] = useState([
    { value: "fixed", label: "Fixed" },
    { value: "Matif", label: "Matif" },
    { value: "Carry", label: "Carry" }
  ]);

  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 [selectedProduct, setSelectedProduct] = useState<any>(null);
  const [products, setProducts] = useState<any[]>([]);

  useEffect(() => {
    // Fetch products data
    fetch("/products/api/productsdata")
      .then(res => res.json())
      .then(setProducts);
  }, []);

  interface QualityParameter {
    name: string;
    stas: string | number | null;
    min?: number;
    max?: number;
    costs?: number;
    currency?: string;
  }

  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: QualityParameter) => param.name);
      setQualityOptions(qualityParams.map((param: string) => ({ value: param, label: param })));
      
      // Update contract with product details
      setContract(prev => ({
        ...prev,
        basicInfo: {
          ...prev.basicInfo,
          goodsCode: product.code || '',
          goods: product.goods || '',
          cropYear: product.cropYear || '',
          origin: product.origin || ''
        },
        productInfo: {
          ...prev.productInfo,
          quality: qualityParams[0] || '',
          qualityTerms: product.qualityParameters
            .filter((param: QualityParameter) => param.stas !== null && param.stas !== undefined && param.stas !== "")
            .map((param: QualityParameter) => {
              let term = `${param.name}: STAS ${param.stas}`;
              if (param.min) term += `, Min ${param.min}`;
              if (param.max) term += `, Max ${param.max}`;
              if (param.costs) term += `, Cost ${param.costs} ${param.currency || 'EUR'}`;
              return term;
            })
            .join(" - ")
        }
      }));
    }
  };

  // Update the productCodeOptions to use the products data
  const productCodeOptions = [
    { value: "", label: t("contracts.fields.goodsCode") },
    ...products.map(product => ({ 
      value: product.code || 'unknown', 
      label: `${product.code || ''}` 
    })).filter(option => option.value && option.value !== 'unknown')
  ];

  // Update the qualityOptionsList
  const qualityOptionsList = [
    { value: "", label: t("contracts.fields.quality") },
    ...qualityOptions.map(quality => ({ 
      value: quality.value, 
      label: quality.label 
    }))
  ];

  useEffect(() => {
    if (contract.basicInfo?.goodsCode) {
      const goodsCode = contract.basicInfo.goodsCode;
      setQualityOptions([
        { value: `USUAL SPECS ${goodsCode} (UM, CS, TW, PROT)`, label: `USUAL SPECS ${goodsCode} (UM, CS, TW, PROT)` }
      ]);
    }
  }, [contract.basicInfo?.goodsCode]);

  useEffect(() => {
    setIsDialogOpen(true);
    // Check if mobile
    const checkMobile = () => {
      setIsMobile(window.innerWidth < 768)
      setIsMobileCheckComplete(true)
    }
    checkMobile()
    window.addEventListener('resize', checkMobile)
    return () => window.removeEventListener('resize', checkMobile)
  }, []);

  useEffect(() => {
    // Fetch existing external contract numbers and other data
    fetch("/contracts/api/contractsdata")
      .then(res => res.json())
      .then((contracts: any[]) => {
        const uniqueContractNumbers = [
          ...new Set(
            contracts.map((c: any) => c.externalContractNo).filter(Boolean)
          )
        ].map(number => ({ value: number, label: number }));
        setExternalContractOptions(uniqueContractNumbers);

        const uniqueCompanies = [
          ...new Set(
            contracts.flatMap((c: any) => [
              c.basicInfo?.sellerCompany,
              c.basicInfo?.buyerCompany
            ]).filter(Boolean) 
          )
        ] as string[];
        setCompanies(uniqueCompanies);

        const uniqueProductCode = [
          ...new Set(
            contracts.flatMap((c: any) => [
              c.basicInfo?.goodsCode,
            ]).filter(Boolean) 
          )
        ] as string[];
        setProductCode(uniqueProductCode);

        const uniqueCropYear = [
          ...new Set(
            contracts.flatMap((c: any) => [
              c.basicInfo?.cropYear,
            ]).filter(Boolean) 
          )
        ] as string[];
        setCropYear(uniqueCropYear);

        const uniqueOrigin = [
          ...new Set(
            contracts.flatMap((c: any) => [
              c.basicInfo?.origin,
            ]).filter(Boolean) 
          )
        ] as string[];
        setOrigin(uniqueOrigin);
      });
  }, []);

  // Add new useEffect for updating goodsFullDescription and qualityTerms
  useEffect(() => {
    if (contract.basicInfo?.goodsCode && contract.basicInfo?.cropYear && contract.basicInfo?.origin) {
      // Fetch product details
      fetch("/products/api/productsdata")
        .then(res => res.json())
        .then((products: any[]) => {
          const product = products.find(p => p.code === contract.basicInfo.goodsCode);
          if (product) {
            // Update goodsFullDescription
            const goodsFullDescription = `${product.goods} ${contract.basicInfo.cropYear} ${contract.basicInfo.origin}`;
            setContract(prev => ({
              ...prev,
              goodsFullDescription,
              goods: product.goods
            }));

            // Update qualityTerms
            if (product.qualityParameters && product.qualityParameters.length > 0) {
              const qualityTerms = product.qualityParameters
                .filter((param: { stas: string | number | null }) => param.stas !== null && param.stas !== undefined && param.stas !== "")
                .map((param: { 
                  name: string; 
                  stas: string | number; 
                  min?: string | number; 
                  max?: string | number; 
                  costs?: string | number; 
                  currency?: string; 
                }) => {
                  let term = `${param.name}: STAS ${param.stas}`;
                  if (param.min) term += `, Min ${param.min}`;
                  if (param.max) term += `, Max ${param.max}`;
                  if (param.costs) term += `, Cost ${param.costs} ${param.currency || 'EUR'}`;
                  return term;
                })
                .join(" - ");
              setContract(prev => ({ ...prev, qualityTerms }));
            }
          }
        });
    }
  }, [contract.basicInfo?.goodsCode, contract.basicInfo?.cropYear, contract.basicInfo?.origin]);

  useEffect(() => {
    // Fetch the last contract number when component mounts
    fetch("/contracts/api/contractsdata")
      .then(res => res.json())
      .then((contracts: any[]) => {
        const currentYear = new Date().getFullYear().toString().slice(-2);
        const brokerPrefixes = ["BRO", "BNK"];
        
        // Find the highest number for each broker prefix for current year
        const lastNumbers = brokerPrefixes.map(prefix => {
          const pattern = new RegExp(`^${prefix}${currentYear}(\\d{4})$`);
          const numbers = contracts
            .map(c => c.contractNumber)
            .filter(num => pattern.test(num))
            .map(num => parseInt(num.slice(-4)));
          return Math.max(0, ...numbers);
        });
        
        setLastContractNumber(Math.max(...lastNumbers).toString().padStart(4, '0'));
      });
  }, []);

  const generateContractNumber = (brokerName: string) => {
    const currentYear = new Date().getFullYear().toString().slice(-2);
    const prefix = brokerName === "BNK BROKERS S.R.L" ? "BRO" : "BNK";
    const nextNumber = (parseInt(lastContractNumber) + 1).toString().padStart(4, '0');
    setLastContractNumber(nextNumber);
    return `${prefix}${currentYear}${nextNumber}`;
  };

  const handleBrokerChange = (broker: string) => {
    setSelectedBroker(broker);
    const newContractNumber = generateContractNumber(broker);
    setContractNumber(newContractNumber);
  };

  const handleDialogConfirm = () => {
    const selectedCompany = currentBroker?.name || "Unknown Company";
    const newContractNumber = generateContractNumber(selectedCompany);
    setContractNumber(newContractNumber);
    
    const prefix = currentBroker?.code ?? "unk";
    const uniqueCode = `${prefix}${Math.floor(100000 + Math.random() * 900000)}`;
    
    setContractCode(uniqueCode);
    setContract((prev: NewContract) => ({
      ...prev,
      broker: selectedBroker,
      contractNumber: newContractNumber
    }));

    setIsDialogOpen(false);
  };

  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 companyOptions = [
    { value: "", label: t("bizz.selectCompany") },
    ...companies.map(company => ({ value: company, label: company }))
  ];

  const personInChargeOptions = [
    {value: "", label: t("contracts.fields.pic")},
    ...picList.map(pic => ({value: pic, label:pic}))
  ]

  const [isDatePickerOpen, setIsDatePickerOpen] = useState(false);

  const handleChange = (field: string, value: any) => {
    setContract((prev: any) => {
      const newContract = { ...prev };
      const fields = field.split('.');
      let current = newContract;
      
      for (let i = 0; i < fields.length - 1; i++) {
        if (!current[fields[i]]) {
          current[fields[i]] = {};
        }
        current = current[fields[i]];
      }
      
      current[fields[fields.length - 1]] = value;
      return newContract;
    });
  }

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault()
    try {
      const response = await fetch(`/contracts/api/contractsdata`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          ...contract,
          id: Date.now(),
          lastModified: new Date().toISOString()
        }),
      })
      if (response.ok) {
        router.push('/contracts/list')
      }
    } catch (error) {
      console.error('Error creating contract:', error)
    }
  }

  const handleSaveContract = async () => {
    try {
      const response = await fetch(`/contracts/api/contractsdata`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          ...contract,
          id: Date.now(),
          lastModified: new Date().toISOString()
        }),
      })
      if (response.ok) {
        router.push('/contracts/list')
      }
    } catch (error) {
      console.error('Error creating contract:', error)
    }
  }

  const handleSend = async () => {
    try {
      // First save the contract
      const saveResponse = await fetch('/contracts/api/contractsdata', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(contract)
      });
      if (!saveResponse.ok) throw new Error('Failed to save contract');

      // Then send the email
      const sendResponse = await fetch('/contracts/api/send-contract', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          contract,
          buyerEmail: contract.basicInfo?.buyerEmail,
          sellerEmail: contract.basicInfo?.sellerEmail
        })
      });
      if (!sendResponse.ok) throw new Error('Failed to send contract');

      alert('Contract created and sent successfully!');
      router.push("/contracts/list");
    } catch (error) {
      alert('Failed to create and send contract.');
    }
  };

  const handleNext = () => {
    const tabs = ["contract-details", "english-details", "commission-details", "document-types", "broker-signatures", "execution-status"];
    const currentIndex = tabs.indexOf(currentTab);
    if (currentIndex < tabs.length - 1) {
      setCurrentTab(tabs[currentIndex + 1]);
    }
  };

  const handlePrevious = () => {
    const tabs = ["contract-details", "english-details", "commission-details", "document-types", "broker-signatures", "execution-status"];
    const currentIndex = tabs.indexOf(currentTab);
    if (currentIndex > 0) {
      setCurrentTab(tabs[currentIndex - 1]);
    }
  };

  const handleCompanyChange = (company: string) => {
    setSelectedCompany(company);
    // Generate contract number based on company code and a random 6-digit number
    const companyCode = company.slice(0, 3).toUpperCase(); // Example: first 3 letters of the company
    const randomNumber = Math.floor(100000 + Math.random() * 900000); // Generate a random 6-digit number
    setContractNumber(`${companyCode}-${randomNumber}`);
  };

  const handleSave = () => {
    // Logic to save the contract
    console.log("Saving contract with number:", contractNumber);
    setIsDialogOpen(false);
  };

  const handleDateChange = (date: Date) => {
    const utcDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
    setContract((prev: any) => ({ ...prev, contractDate: utcDate.toISOString().split('T')[0] }));
    setIsDatePickerOpen(false);
  };

  const statusOptions = [
    { value: "Draft", label: "Draft" },
    { value: "Open", label: "Open" },
    { value: "Closed", label: "Closed" },
    { value: "VII 24", label: "VII 24" },
    { value: "VIII 24", label: "VIII 24" }
  ];

  const getTabTitle = (tab: string) => {
    switch(tab) {
      case "contract-details": return t("contracts.sections.contractProductDetails");
      case "english-details": return "English Details";
      case "commission-details": return t("contracts.sections.commissionDetails");
      case "document-types": return t("contracts.sections.documentTypes");
      case "broker-signatures": return t("contracts.sections.brokerSignatures");
      case "execution-status": return t("contracts.sections.executionStatus");
      default: return "";
    }
  };

  const [parityOptions] = useState([
    { value: "FCA", label: "FCA" },
    { value: "DAP", label: "DAP" },
    { value: "FOB", label: "FOB" },
    { value: "CIF", label: "CIF" }
  ]);

  const getDeliveryConditionText = (parity: string, transport: string) => {
    switch(parity) {
      case "FCA":
        return `In cazul livrarilor folosind transportul ${transport} si paritatea FCA, marfa va fi livrata la adresa furnizorului.`;
      case "DAP":
        return `In cazul livrarilor folosind transportul ${transport} si paritatea DAP, marfa va fi livrata la adresa destinatarului.`;
      case "FOB":
        return `In cazul livrarilor folosind transportul ${transport} si paritatea FOB, marfa va fi livrata la portul de incarcare.`;
      case "CIF":
        return `In cazul livrarilor folosind transportul ${transport} si paritatea CIF, marfa va fi livrata la portul de descarcare.`;
      default:
        return "";
    }
  };

  useEffect(() => {
    if (contract.delivery?.parity && contract.delivery?.transport) {
      const conditionText = getDeliveryConditionText(contract.delivery.parity, contract.delivery.transport);
      setContract({
        ...contract,
        delivery: {
          ...contract.delivery,
          conditions: conditionText
        }
      });
    }
  }, [contract.delivery?.parity, contract.delivery?.transport]);

  // Move these options declarations before the return statement
  const cropYearOptions = [
    { value: "", label: t("contracts.fields.cropYear") },
    ...cropYear.map((year: string) => ({ value: year, label: year }))
  ];

  const originOptions = [
    { value: "", label: t("contracts.fields.origin") },
    ...origin.map((orig: string) => ({ value: orig, label: orig }))
  ];

  if (loading) return <div className="p-8">Loading...</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={t("contracts.newcontract")}/>
        <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">New Contract</h2>
              </div>
              <div className="flex gap-2">
                <Button variant="outline" onClick={() => router.back()}>
                  Cancel
                </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 === "contract-details" && <BuildingIcon className="h-4 w-4" />}
                    {currentTab === "english-details" && <IconMessageLanguage className="h-4 w-4" />}
                    {currentTab === "commission-details" && <DollarIcon className="h-4 w-4" />}
                    {currentTab === "document-types" && <IconFileTypeDoc className="h-4 w-4" />}
                    {currentTab === "broker-signatures" && <IconSignature className="h-4 w-4" />}
                    {currentTab === "execution-status" && <IconHourglassEmpty className="h-4 w-4" />}
                    {getTabTitle(currentTab)}
                  </div>
                </div>
              </div>
            )}

            <form onSubmit={handleSubmit} className="px-4 lg:px-6">
              <Tabs value={currentTab} onValueChange={setCurrentTab} className="w-full">
                {!isMobile && (
                  <TabsList className="px-4 lg:px-6 lg:w-full lg:h-14">
                    <TabsTrigger value="contract-details" className="flex items-center gap-2 lg:text-lg">
                      <BuildingIcon className="h-4 w-4" />
                      {t("contracts.sections.contractProductDetails")}
                    </TabsTrigger>
                    <TabsTrigger value="english-details" className="flex items-center gap-2 lg:text-lg">
                      <IconMessageLanguage className="h-4 w-4"/>
                      English Details
                    </TabsTrigger>
                    <TabsTrigger value="commission-details" className="flex items-center gap-2 lg:text-lg">
                      <DollarIcon className="h-4 w-4" />
                      Commission Details
                    </TabsTrigger>
                    <TabsTrigger value="document-types" className="flex items-center gap-2 lg:text-lg">
                      <IconFileTypeDoc className="h-4 w-4" />
                      Document Types
                    </TabsTrigger>
                    <TabsTrigger value="broker-signatures" className="flex items-center gap-2 lg:text-lg">
                      <IconSignature className="h-4 w-4" />
                      Broker Signatures
                    </TabsTrigger>
                    <TabsTrigger value="execution-status" className="flex items-center gap-2 lg:text-lg">
                      <IconHourglassEmpty className="h-4 w-4" />
                      Execution Status
                    </TabsTrigger>
                  </TabsList>
                )}

                <div className={isMobile ? "block" : "contents"}>
                  {/* Contract Details Tab */}
                  <TabsContent 
                    value="contract-details" 
                    className="px-4 lg:px-6"
                    style={{ display: isMobile && currentTab !== "contract-details" ? "none" : "block" }}
                  >
                    <Card>
                      <CardHeader>
                        <CardTitle className="flex items-center gap-2">
                          <FileText className="h-5 w-5" />
                          {t("contracts.sections.contractProductDetails")}
                        </CardTitle>
                      </CardHeader>
                      <CardContent className="space-y-4">
                        <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
                          <div className="flex flex-col gap-2">
                            <Label>{t("contracts.fields.contractNumber")}</Label>
                            <Input value={contractNumber} readOnly />
                          </div>
                          <div className="flex flex-col gap-2">
                            <Label>{t("contracts.fields.brokerageCompany")}</Label>
                            <Input value={selectedBroker} readOnly />
                          </div>
                          <div className="flex flex-col gap-2">
                            <Label>{t("contracts.fields.contractDate")}</Label>
                            <Popover>
                              <PopoverTrigger asChild>
                                <Button
                                  variant={"outline"}
                                  className={cn(
                                    "w-full justify-start text-left font-normal",
                                    !contract.contractDate && "text-muted-foreground"
                                  )}
                                >
                                  <CalendarIcon className="mr-2 h-4 w-4" />
                                  {contract.contractDate ? format(new Date(contract.contractDate), "dd/MM/yyyy") : format(new Date(), "dd/MM/yyyy")}
                                </Button>
                              </PopoverTrigger>
                              <PopoverContent className="w-auto p-0">
                                <Calendar
                                  mode="single"
                                  selected={contract.contractDate ? new Date(contract.contractDate) : new Date()}
                                  onSelect={(date) => {
                                    if (date) {
                                      const utcDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
                                      setContract((prev: any) => ({ ...prev, contractDate: utcDate.toISOString().split('T')[0] }));
                                    }
                                  }}
                                  initialFocus
                                />
                              </PopoverContent>
                            </Popover>
                          </div>
                          <div className="flex flex-col gap-2">
                            <Label>{t("contracts.fields.status")}</Label>
                            <Select 
                              value={contract.status} 
                              onValueChange={v => handleChange("status", v)}
                            >
                              <SelectTrigger className="w-full"><SelectValue /></SelectTrigger>
                              <SelectContent>
                                {statusOptions.map(option => (
                                  <SelectItem key={option.value} value={option.value}>
                                    {option.label}
                                  </SelectItem>
                                ))}
                              </SelectContent>
                            </Select>
                          </div>
                          <div className="flex flex-col gap-2">
                            <Label>{t("contracts.fields.sellerCompany")}</Label>
                            <ComboboxFull 
                              items={companyOptions}
                              value={selectedCompany}
                              onValueChange={(value) => {
                                setSelectedCompany(value);
                                setContract({ 
                                  ...contract, 
                                  basicInfo: { 
                                    ...contract.basicInfo, 
                                    sellerCompany: value 
                                  } 
                                });
                              }}
                              placeholder={t("bizz.selectCompany")}
                              emptyText={t("bizz.noCompanies")}
                              showCreateOption={true}
                              onCreateNew={handleCreateCompany}
                            />
                          </div>
                          <div className="flex flex-col gap-2">
                            <Label>{t("contracts.fields.buyerCompany")}</Label>
                            <ComboboxFull 
                              items={companyOptions}
                              value={selectedBuyerCompany}
                              onValueChange={(value) => {
                                setSelectedBuyerCompany(value);
                                setContract({ 
                                  ...contract, 
                                  basicInfo: { 
                                    ...contract.basicInfo, 
                                    buyerCompany: value 
                                  } 
                                });
                              }}
                              placeholder={t("bizz.selectCompany")}
                              emptyText={t("bizz.noCompanies")}
                              showCreateOption={true}
                              onCreateNew={handleCreateCompany}
                            />
                          </div>
                          <div className="flex flex-col gap-2">
                            <Label>{t("contracts.fields.goodsCode")}</Label>
                            <ComboboxFull 
                              items={productCodeOptions}
                              value={selectedProductCode}
                              onValueChange={(value) => {
                                setSelectedProductCode(value);
                                handleProductCodeChange(value);
                              }}
                              placeholder={t("contracts.fields.goodsCode")}
                              emptyText={t("bizz.noProductCodes")}
                              showCreateOption={true}
                              onCreateNew={(value) => {
                                setProductCode([...productCode, value]);
                                setSelectedProductCode(value);
                              }}
                            />
                          </div>
                          <div className="flex flex-col gap-2">
                            <Label>{t("contracts.fields.goods")}</Label>
                            <Input value={contract.goods} readOnly />
                          </div>
                          <div className="flex flex-col gap-2">
                          <Label>{t("contracts.fields.cropYear")}</Label>
                          <ComboboxFull 
                            items={cropYearOptions}
                            value={selectedCropYear}
                            onValueChange={(value) => {
                              setSelectedCropYear(value);
                              setContract({ 
                                ...contract, 
                                basicInfo: { 
                                  ...contract.basicInfo, 
                                  cropYear: value 
                                } 
                              });
                            }}
                            placeholder={t("contracts.fields.cropYear")}
                            emptyText={t("bizz.noCropYears")}
                            showCreateOption={true}
                            onCreateNew={(value) => {
                              setCropYear([...cropYear, value]);
                              setSelectedCropYear(value);
                            }}
                          />
                        </div>
                          <div className="flex flex-col gap-2">
                          <Label>{t("contracts.fields.origin")}</Label>
                          <ComboboxFull 
                            items={originOptions}
                            value={selectedOrigin}
                            onValueChange={(value) => {
                              setSelectedOrigin(value);
                              setContract({ 
                                ...contract, 
                                basicInfo: { 
                                  ...contract.basicInfo, 
                                  origin: value 
                                } 
                              });
                            }}
                            placeholder={t("contracts.fields.origin")}
                            emptyText={t("bizz.noOrigins")}
                            showCreateOption={true}
                            onCreateNew={(value) => {
                              setOrigin([...origin, value]);
                              setSelectedOrigin(value);
                            }}
                          />
                        </div>
                        </div>
                        <div className="flex flex-col gap-2 mt-2">
                          <Label>{t("contracts.fields.goodsFullDescription")}</Label>
                          <Textarea value={contract.goodsFullDescription} onChange={e => handleChange("goodsFullDescription", e.target.value)} />
                        </div>
                        <div className="flex flex-col gap-2 mt-2">
                          <Label>{t("contracts.fields.qualityTerms")}</Label>
                          <Textarea value={contract.qualityTerms} onChange={e => handleChange("qualityTerms", e.target.value)} />
                        </div>
                        <div className="grid grid-cols-1 lg:grid-cols-3 gap-4 mt-2">
                          <div className="flex flex-col gap-2">
                            <Label>{t("contracts.fields.quantitymts")}</Label>
                            <ComboboxFull 
                              items={quantityOptions}
                              value={contract.quantitymts?.toString() || ""}
                              onValueChange={(value) => {
                                setContract({ 
                                  ...contract, 
                                  quantitymts: parseInt(value) 
                                });
                              }}
                              placeholder="Select quantity"
                              emptyText="No quantity options"
                            />
                          </div>
                          <div className="flex flex-col gap-2">
                            <Label>{t("contracts.fields.tolerance")}</Label>
                            <div className="flex gap-2">
                              <Select 
                                value={contract.productInfo?.toleranceType || "percentage"} 
                                onValueChange={val => {
                                  const defaultTolerance = val === "percentage" ? "5" : "25";
                                  setContract({ 
                                    ...contract, 
                                    productInfo: { 
                                      ...contract.productInfo, 
                                      toleranceType: val,
                                      tolerance: defaultTolerance
                                    } 
                                  });
                                }}
                              >
                                <SelectTrigger className="w-full">
                                  <SelectValue />
                                </SelectTrigger>
                                <SelectContent>
                                  {toleranceTypeOptions.map(option => (
                                    <SelectItem key={option.value} value={option.value}>
                                      {option.label}
                                    </SelectItem>
                                  ))}
                                </SelectContent>
                              </Select>
                              <Select 
                                value={contract.productInfo?.tolerance || (contract.productInfo?.toleranceType === "percentage" ? "5" : "25")} 
                                onValueChange={val => setContract({ 
                                  ...contract, 
                                  productInfo: { 
                                    ...contract.productInfo, 
                                    tolerance: val 
                                  } 
                                })}
                              >
                                <SelectTrigger className="w-full">
                                  <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">
                            <Label>{t("contracts.fields.pricePerMT")}</Label>
                            <Input type="number" value={contract.pricePerMT} onChange={e => handleChange("pricePerMT", e.target.value)} />
                          </div>
                          <div className="flex flex-col gap-2">
                            <Label>{t("contracts.fields.priceCurrency")}</Label>
                            <Select value={contract.priceCurrency} onValueChange={v => handleChange("priceCurrency", v)}>
                              <SelectTrigger className="w-full"><SelectValue /></SelectTrigger>
                              <SelectContent>
                                {priceCurrencies.map(c => <SelectItem key={c} value={c}>{c}</SelectItem>)}
                              </SelectContent>
                            </Select>
                          </div>
                          <div className="flex flex-col gap-2">
                            <Label>{t("contracts.fields.priceType")}</Label>
                            <ComboboxFull 
                              items={priceTypeOptions}
                              value={contract.financialInfo?.priceType || ""}
                              onValueChange={(value) => {
                                setContract({ 
                                  ...contract, 
                                  financialInfo: { 
                                    ...contract.financialInfo, 
                                    priceType: value 
                                  } 
                                });
                              }}
                              placeholder="Select price type"
                              emptyText="No price type options"
                            />
                          </div>
                          <div className="flex flex-col gap-2">
                            <Label>{t("contracts.fields.carryOrSpreadPrice")}</Label>
                            <Input value={contract.carryOrSpreadPrice} onChange={e => handleChange("carryOrSpreadPrice", e.target.value)} />
                          </div>
                          <div className="flex flex-col gap-2">
                            <Label>{t("contracts.fields.incoterms")}</Label>
                            <ComboboxFull 
                              items={parityOptions}
                              value={contract.incoterms}
                              onValueChange={(value) => {
                                setContract({ 
                                  ...contract, 
                                  incoterms: value 
                                });
                              }}
                              placeholder="Select incoterms"
                              emptyText="No incoterms options"
                            />
                          </div>
                          <div className="flex flex-col gap-2">
                            <Label>{t("contracts.fields.deliveryPlace")}</Label>
                            <ComboboxFull 
                              items={locationOptions}
                              value={contract.deliveryPlace}
                              onValueChange={(value) => {
                                setContract({ 
                                  ...contract, 
                                  deliveryPlace: value 
                                });
                              }}
                              placeholder="Select delivery place"
                              emptyText="No delivery places"
                              showCreateOption={true}
                              onCreateNew={(value) => {
                                setLocationOptions([...locationOptions, { value: value, label: value }]);
                                setContract({ 
                                  ...contract, 
                                  deliveryPlace: value 
                                });
                              }}
                            />
                          </div>
                          <div className="flex flex-col gap-2">
                            <Label>{t("contracts.fields.transport")}</Label>
                            <ComboboxFull 
                              items={transportOptions}
                              value={contract.delivery?.transport || ""}
                              onValueChange={(value) => {
                                setContract({ 
                                  ...contract, 
                                  delivery: { 
                                    ...contract.delivery, 
                                    transport: value 
                                  } 
                                });
                              }}
                              placeholder="Select transport"
                              emptyText="No transport options"
                            />
                          </div>
                        </div>
                        <div className="flex flex-col gap-2 mt-2">
                          <Label>{t("contracts.fields.paymentTerms")}</Label>
                          <Textarea value={contract.paymentTerms} onChange={e => handleChange("paymentTerms", e.target.value)} />
                        </div>
                        <div className="grid grid-cols-2 gap-4 mt-2">
                        <div className="flex flex-col gap-2">
                          <Label>{t("contracts.fields.deliveryDateFrom")}</Label>
                          <Popover>
                            <PopoverTrigger asChild>
                              <Button
                                variant={"outline"}
                                className={cn(
                                  "w-full justify-start text-left font-normal",
                                  !contract.deliveryDateFrom && "text-muted-foreground"
                                )}
                              >
                                <CalendarIcon className="mr-2 h-4 w-4" />
                                {contract.deliveryDateFrom ? format(new Date(contract.deliveryDateFrom), "dd/MM/yyyy") : "Pick a date"}
                              </Button>
                            </PopoverTrigger>
                            <PopoverContent className="w-auto p-0">
                              <Calendar
                                mode="single"
                                selected={contract.deliveryDateFrom ? new Date(contract.deliveryDateFrom) : undefined}
                                onSelect={(date) => handleChange("deliveryDateFrom", date?.toISOString())}
                                initialFocus
                              />
                            </PopoverContent>
                          </Popover>
                        </div>

                        <div className="flex flex-col gap-2">
                          <Label>{t("contracts.fields.deliveryDateTo")}</Label>
                          <Popover>
                            <PopoverTrigger asChild>
                              <Button
                                variant={"outline"}
                                className={cn(
                                  "w-full justify-start text-left font-normal",
                                  !contract.deliveryDateTo && "text-muted-foreground"
                                )}
                              >
                                <CalendarIcon className="mr-2 h-4 w-4" />
                                {contract.deliveryDateTo ? format(new Date(contract.deliveryDateTo), "dd/MM/yyyy") : "Pick a date"}
                              </Button>
                            </PopoverTrigger>
                            <PopoverContent className="w-auto p-0">
                              <Calendar
                                mode="single"
                                selected={contract.deliveryDateTo ? new Date(contract.deliveryDateTo) : undefined}
                                onSelect={(date) => handleChange("deliveryDateTo", date?.toISOString())}
                                initialFocus
                              />
                            </PopoverContent>
                          </Popover>
                        </div>
                        </div>
                        <div className="flex flex-col gap-2 mt-2">
                          <Label>{t("contracts.fields.deliveryTermSBOption")}</Label>
                          <Input value={contract.deliveryTermSBOption} onChange={e => handleChange("deliveryTermSBOption", e.target.value)} />
                        </div>
                        <div className="flex flex-col gap-2 mt-2">
                          <Label>{t("contracts.fields.otherTerms")}</Label>
                          <Textarea value={contract.otherTerms} onChange={e => handleChange("otherTerms", e.target.value)} />
                        </div>
                        <div className="flex flex-col gap-2 mt-2">
                          <Label>{t("contracts.fields.externalContractNo")}</Label>
                          <ComboboxFull 
                            items={externalContractOptions}
                            value={contract.externalContractNo}
                            onValueChange={(value) => {
                              setContract({ 
                                ...contract, 
                                externalContractNo: value 
                              });
                            }}
                            placeholder="Select external contract number"
                            emptyText="No external contract numbers"
                            showCreateOption={true}
                            onCreateNew={(value) => {
                              setExternalContractOptions([...externalContractOptions, { value: value, label: value }]);
                              setContract({ 
                                ...contract, 
                                externalContractNo: value 
                              });
                            }}
                          />
                        </div>
                      </CardContent>
                    </Card>
                  </TabsContent>

                  {/* English Details Tab */}
                  <TabsContent 
                    value="english-details" 
                    className="px-4 lg:px-6"
                    style={{ display: isMobile && currentTab !== "english-details" ? "none" : "block" }}
                  >
                    <Card>
                      <CardHeader>
                        <CardTitle className="flex items-center gap-2">
                          <Globe className="h-5 w-5" />
                          {t("contracts.sections.englishDetails")}
                        </CardTitle>
                      </CardHeader>
                      <CardContent className="space-y-4">
                        <div className="flex flex-col gap-2">
                          <Label>{t("contracts.fields.goodsFullDescriptionENG")}</Label>
                          <Textarea value={contract.goodsFullDescriptionENG} onChange={e => handleChange("goodsFullDescriptionENG", e.target.value)} />
                        </div>
                        <div className="flex flex-col gap-2 mt-2">
                          <Label>{t("contracts.fields.qualityTermsENG")}</Label>
                          <Textarea value={contract.qualityTermsENG} onChange={e => handleChange("qualityTermsENG", e.target.value)} />
                        </div>
                        <div className="flex flex-col gap-2 mt-2">
                          <Label>{t("contracts.fields.quantityToleranceENG")}</Label>
                          <Input value={contract.quantityToleranceENG} onChange={e => handleChange("quantityToleranceENG", e.target.value)} />
                        </div>
                        <div className="flex flex-col gap-2 mt-2">
                          <Label>{t("contracts.fields.deliveryPlaceENG")}</Label>
                          <Input value={contract.deliveryPlaceENG} onChange={e => handleChange("deliveryPlaceENG", e.target.value)} />
                        </div>
                        <div className="flex flex-col gap-2 mt-2">
                          <Label>{t("contracts.fields.priceCurrencyENG")}</Label>
                          <Select value={contract.priceCurrencyENG} onValueChange={v => handleChange("priceCurrencyENG", v)}>
                            <SelectTrigger className="w-full"><SelectValue /></SelectTrigger>
                            <SelectContent>
                              {priceCurrencies.map(c => <SelectItem key={c} value={c}>{c}</SelectItem>)}
                            </SelectContent>
                          </Select>
                        </div>
                        <div className="flex flex-col gap-2 mt-2">
                          <Label>{t("contracts.fields.carryOrSpreadPriceENG")}</Label>
                          <Input value={contract.carryOrSpreadPriceENG} onChange={e => handleChange("carryOrSpreadPriceENG", e.target.value)} />
                        </div>
                        <div className="flex flex-col gap-2 mt-2">
                          <Label>{t("contracts.fields.paymentTermsENG")}</Label>
                          <Textarea value={contract.paymentTermsENG} onChange={e => handleChange("paymentTermsENG", e.target.value)} />
                        </div>
                        <div className="flex flex-col gap-2 mt-2">
                          <Label>{t("contracts.fields.deliveryTermSBOptionENG")}</Label>
                          <Input value={contract.deliveryTermSBOptionENG} onChange={e => handleChange("deliveryTermSBOptionENG", e.target.value)} />
                        </div>
                        <div className="flex flex-col gap-2 mt-2">
                          <Label>{t("contracts.fields.otherTermsENG")}</Label>
                          <Textarea value={contract.otherTermsENG} onChange={e => handleChange("otherTermsENG", e.target.value)} />
                        </div>
                      </CardContent>
                    </Card>
                  </TabsContent>

                  {/* Commission Details Tab */}
                  <TabsContent 
                    value="commission-details" 
                    className="px-4 lg:px-6"
                    style={{ display: isMobile && currentTab !== "commission-details" ? "none" : "block" }}
                  >
                    <Card>
                      <CardHeader>
                        <CardTitle className="flex items-center gap-2">
                          <Percent className="h-5 w-5" />
                          {t("contracts.sections.commissionDetails")}
                        </CardTitle>
                      </CardHeader>
                      <CardContent className="space-y-4">
                        <div className="flex flex-col gap-2">
                          <Label>{t("contracts.fields.whoIsPayingCommission")}</Label>
                          <Select 
                            value={contract.whoIsPayingCommission} 
                            onValueChange={val => handleChange("whoIsPayingCommission", val)}
                          >
                            <SelectTrigger>
                              <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                              {whoIsPayingOptions.map(option => (
                                <SelectItem key={option.value} value={option.value}>
                                  {option.label}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        </div>

                        {contract.whoIsPayingCommission === "S" && (
                          <>
                            <div className="grid grid-cols-1 lg:grid-cols-2  gap-2">
                              <div className="flex flex-col gap-2 ">
                                <Label>{t("contracts.fields.sellerCommission")}</Label>
                                <div className="flex gap-2">
                                  <Input 
                                    type="number" 
                                    value={contract.sellerCommission} 
                                    onChange={e => handleChange("sellerCommission", e.target.value)} 

                                  />
                                  
                                </div>
                              </div>
                              <div className=" flex flex-col gap-2 ">
                                <Label>{t("contracts.fields.sellerCommissionCurrency")}</Label>
                                <Select 
                                    value={contract.sellerCommissionCurrency} 
                                    onValueChange={val => handleChange("sellerCommissionCurrency", val)}
                                  >
                                    <SelectTrigger className="w-1/2">
                                      <SelectValue />
                                    </SelectTrigger>
                                    <SelectContent>
                                      {currencyOptions.map(option => (
                                        <SelectItem key={option.value} value={option.value}>
                                          {option.label}
                                        </SelectItem>
                                      ))}
                                    </SelectContent>
                                  </Select>
                                </div>
                            </div>
                          </>
                        )}

                        {contract.whoIsPayingCommission === "B" && (
                          <>
                          <div className="grid grid-cols-1 lg:grid-cols-2 gap-2">
                            <div className="flex flex-col gap-2">
                              <Label>{t("contracts.fields.buyerCommission")}</Label>
                              <Input 
                                  type="number" 
                                  value={contract.buyerCommission} 
                                  onChange={e => handleChange("buyerCommission", e.target.value)} 

                                />
                            </div>
                            <div className="flex flex-col gap-2 ">
                                  <Label>{t("contracts.fields.buyerCommissionCurrency")}</Label>
                                  <Select 
                                    value={contract.buyerCommissionCurrency} 
                                    onValueChange={val => handleChange("buyerCommissionCurrency", val)}
                                  >
                                    <SelectTrigger className="w-1/2">
                                      <SelectValue />
                                    </SelectTrigger>
                                    <SelectContent>
                                      {currencyOptions.map(option => (
                                        <SelectItem key={option.value} value={option.value}>
                                          {option.label}
                                        </SelectItem>
                                      ))}
                                    </SelectContent>
                                  </Select>
                            </div>
                          </div>
                          </>
                        )}

                        {contract.whoIsPayingCommission === "S+B" && (
                          <>
                            <div className="grid grid-cols-1 lg:grid-cols-2 gap-2">
                              <div className="flex flex-col gap-2">
                                <Label>{t("contracts.fields.sellerCommission")}</Label>
                                <Input 
                                  type="number" 
                                  value={contract.sellerCommission} 
                                  onChange={e => handleChange("sellerCommission", e.target.value)} 
                                />
                              </div>
                              <div className="flex flex-col gap-2">
                                <Label>{t("contracts.fields.sellerCommissionCurrency")}</Label>
                                <Select 
                                  value={contract.sellerCommissionCurrency} 
                                  onValueChange={val => handleChange("sellerCommissionCurrency", val)}
                                >
                                  <SelectTrigger>
                                    <SelectValue />
                                  </SelectTrigger>
                                  <SelectContent>
                                    {currencyOptions.map(option => (
                                      <SelectItem key={option.value} value={option.value}>
                                        {option.label}
                                      </SelectItem>
                                    ))}
                                  </SelectContent>
                                </Select>
                              </div>
                              <div className="flex flex-col gap-2">
                                <Label>{t("contracts.fields.buyerCommission")}</Label>
                                <Input 
                                  type="number" 
                                  value={contract.buyerCommission} 
                                  onChange={e => handleChange("buyerCommission", e.target.value)} 
                                />
                              </div>
                              <div className="flex flex-col gap-2">
                                <Label>{t("contracts.fields.buyerCommissionCurrency")}</Label>
                                <Select 
                                  value={contract.buyerCommissionCurrency} 
                                  onValueChange={val => handleChange("buyerCommissionCurrency", val)}
                                >
                                  <SelectTrigger>
                                    <SelectValue />
                                  </SelectTrigger>
                                  <SelectContent>
                                    {currencyOptions.map(option => (
                                      <SelectItem key={option.value} value={option.value}>
                                        {option.label}
                                      </SelectItem>
                                    ))}
                                  </SelectContent>
                                </Select>
                              </div>
                            </div>
                          </>
                        )}

                        {/* Signatures Tab */}
                        

                        

                        {/* Execution Tab */}
                        
                      </CardContent>
                    </Card>
                  </TabsContent>

                  {/* Document Types Tab */}
                  <TabsContent 
                    value="document-types" 
                    className="px-4 lg:px-6"
                    style={{ display: isMobile && currentTab !== "document-types" ? "none" : "block" }}
                  >
                    <Card>
                      <CardHeader>
                        <CardTitle className="flex items-center gap-2">
                          <IconFileTypeDoc className="h-5 w-5" />
                          {t("contracts.sections.documentTypes")}
                        </CardTitle>
                      </CardHeader>
                      <CardContent className="space-y-4">
                        <div className="grid grid-cols-2 gap-4">
                          <div className="flex flex-col gap-2">
                            <Label>{t("contracts.fields.contractDraft")}</Label>
                            <Input value={contract.contractDraft} onChange={e => handleChange("contractDraft", e.target.value)} />
                          </div>
                          <div className="flex flex-col gap-2">
                            <Label>{t("contracts.fields.addTypeLb")}</Label>
                            <Input value={contract.addTypeLb} onChange={e => handleChange("addTypeLb", e.target.value)} />
                          </div>
                          <div className="flex flex-col gap-2">
                            <Label>{t("contracts.fields.artTypeLb")}</Label>
                            <Input value={contract.artTypeLb} onChange={e => handleChange("artTypeLb", e.target.value)} />
                          </div>
                        </div>
                      </CardContent>
                    </Card>
                  </TabsContent>

                  {/* Broker Signatures Tab */}
                  <TabsContent 
                    value="broker-signatures" 
                    className="px-4 lg:px-6"
                    style={{ display: isMobile && currentTab !== "broker-signatures" ? "none" : "block" }}
                  >
                    <Card>
                      <CardHeader>
                        <CardTitle className="flex items-center gap-2">
                          <IconSignature className="h-5 w-5" />
                          {t("contracts.sections.brokerSignatures")}
                        </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">
                            <Label>{t("contracts.fields.sellerBrokerCode")}</Label>
                            <Input value={contract.sellerBrokerCode} onChange={e => handleChange("sellerBrokerCode", e.target.value)} />
                          </div>
                          <div className="flex flex-col gap-2">
                            <Label>{t("contracts.fields.buyerBrokerCode")}</Label>
                            <Input value={contract.buyerBrokerCode} onChange={e => handleChange("buyerBrokerCode", e.target.value)} />
                          </div>
                          <div className="flex flex-col gap-2">
                            <Label>{t("contracts.fields.initialQuantity")}</Label>
                            <Input type="number" value={contract.initialQuantity} onChange={e => handleChange("initialQuantity", e.target.value)} />
                          </div>
                          <div className="flex flex-col gap-2">
                            <Label>{t("contracts.fields.guaranteesBO")}</Label>
                            <Input value={contract.guaranteesBO} onChange={e => handleChange("guaranteesBO", e.target.value)} />
                          </div>
                          <div className="flex flex-col gap-2">
                            <div className="flex flex-col gap-2">
                              <Label>{t("contracts.fields.statusBO")}</Label>
                              <Select 
                                value={contract.statusBO} 
                                onValueChange={val => handleChange("statusBO", val)}
                              >
                                <SelectTrigger className="w-full">
                                  <SelectValue />
                                </SelectTrigger>
                                <SelectContent>
                                  {boStatusOptions.map(option => (
                                    <SelectItem key={option.value} value={option.value}>
                                      {option.label}
                                    </SelectItem>
                                  ))}
                                </SelectContent>
                              </Select>
                            </div>
                          </div>
                          <div className="flex flex-col gap-2">
                          <Label>{t("contracts.fields.sellerSigned")}</Label>
                          <Select 
                            value={contract.sellerSigned} 
                            onValueChange={val => handleChange("sellerSigned", val)}
                          >
                            <SelectTrigger className="w-full">
                              <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                              {signedOptions.map(option => (
                                <SelectItem key={option.value} value={option.value}>
                                  {option.label}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        </div>

                        <div className="flex flex-col gap-2">
                          <Label>{t("contracts.fields.buyerSigned")}</Label>
                          <Select 
                            value={contract.buyerSigned} 
                            onValueChange={val => handleChange("buyerSigned", val)}
                          >
                            <SelectTrigger className="w-full">
                              <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                              {signedOptions.map(option => (
                                <SelectItem key={option.value} value={option.value}>
                                  {option.label}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        </div>

                        <div className="flex flex-col gap-2 ">
                          <Label>{t("contracts.fields.brokerSigned")}</Label>
                          <Select 
                            value={contract.brokerSigned} 
                            onValueChange={val => handleChange("brokerSigned", val)}
                          >
                            <SelectTrigger className="w-full">
                              <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                              {signedOptions.map(option => (
                                <SelectItem key={option.value} value={option.value}>
                                  {option.label}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        </div>
                        </div>
                      </CardContent>
                    </Card>
                  </TabsContent>

                  {/* Execution Status Tab */}
                  <TabsContent 
                    value="execution-status" 
                    className="px-4 lg:px-6"
                    style={{ display: isMobile && currentTab !== "execution-status" ? "none" : "block" }}
                  >
                    <Card>
                      <CardHeader>
                        <CardTitle className="flex items-center gap-2">
                          <ClipboardCheck className="h-5 w-5" />
                          {t("contracts.sections.executionStatus")}
                        </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">
                            <Label>{t("contracts.fields.executedQuantity")}</Label>
                            <Input type="number" value={contract.executedQuantity} onChange={e => handleChange("executedQuantity", e.target.value)} />
                          </div>
                          <div className="flex flex-col gap-2">
                            <Label>{t("contracts.fields.remainingToBeExecuted")}</Label>
                            <Input type="number" value={contract.remainingToBeExecuted} onChange={e => handleChange("remainingToBeExecuted", e.target.value)} />
                          </div>
                          <div className="flex flex-col gap-2">
                            <Label>{t("contracts.fields.commissionInvoice")}</Label>
                            <Input type="number" value={contract.commissionInvoice} onChange={e => handleChange("commissionInvoice", e.target.value)} />
                          </div>
                          <div className="flex flex-col gap-2">
                            <Label>{t("contracts.fields.totalCommisionEUR/mt")}</Label>
                            <Input type="number" value={contract.totalCommisionEURmt} onChange={e => handleChange("totalCommisionEURmt", e.target.value)} />
                          </div>
                          <div className="flex flex-col gap-2">
                            <Label>{t("contracts.fields.totalValueCommissionEUR")}</Label>
                            <Input type="number" value={contract.totalValueCommissionEUR} onChange={e => handleChange("totalValueCommissionEUR", e.target.value)} />
                          </div>
                          <div className="flex flex-col gap-2">
                            <Label>{t("contracts.fields.sellerBrokerCommission")}</Label>
                            <Input type="number" value={contract.sellerBrokerCommission} onChange={e => handleChange("sellerBrokerCommission", e.target.value)} />
                          </div>
                          <div className="flex flex-col gap-2">
                            <Label>{t("contracts.fields.buyerBrokerCommission")}</Label>
                            <Input type="number" value={contract.buyerBrokerCommission} onChange={e => handleChange("buyerBrokerCommission", e.target.value)} />
                          </div>
                          <div className="flex flex-col gap-2">
                          <Label>{t("contracts.fields.contractCurrencyDate")}</Label>
                          <Popover>
                            <PopoverTrigger asChild>
                              <Button
                                variant={"outline"}
                                className={cn(
                                  "w-full justify-start text-left font-normal",
                                  !contract.contractCurrencyDate && "text-muted-foreground"
                                )}
                              >
                                <CalendarIcon className="mr-2 h-4 w-4" />
                                {contract.contractCurrencyDate ? format(new Date(contract.contractCurrencyDate), "dd/MM/yyyy") : "Pick a date"}
                              </Button>
                            </PopoverTrigger>
                            <PopoverContent className="w-auto p-0">
                              <Calendar
                                mode="single"
                                selected={contract.contractCurrencyDate ? new Date(contract.contractCurrencyDate) : undefined}
                                onSelect={(date) => handleChange("contractCurrencyDate", date?.toISOString())}
                                initialFocus
                              />
                            </PopoverContent>
                          </Popover>
                        </div>
                          <div className="flex flex-col gap-2">
                            <Label>{t("contracts.fields.sellerExchangeRate")}</Label>
                            <Input type="number" value={contract.sellerExchangeRate} onChange={e => handleChange("sellerExchangeRate", e.target.value)} />
                          </div>
                          
                          <div className="flex flex-col gap-2">
                            <Label>{t("contracts.fields.buyerExchangeRate")}</Label>
                            <Input type="number" value={contract.buyerExchangeRate} onChange={e => handleChange("buyerExchangeRate", e.target.value)} />
                          </div>
                          <div className="flex flex-col gap-2">
                            <Label>{t("contracts.fields.defaultQTY")}</Label>
                            <Input value={contract.defaultQTY} onChange={e => handleChange("defaultQTY", e.target.value)} />
                          </div>
                          <div className="flex flex-col gap-2">
                            <Label>{t("contracts.fields.executionYear")}</Label>
                            <Select value={contract.executionYear} onValueChange={v => handleChange("executionYear", v)}>
                              <SelectTrigger className="w-full"><SelectValue /></SelectTrigger>
                              <SelectContent>
                                {cropYears.map(y => <SelectItem key={y} value={y}>{y}</SelectItem>)}
                              </SelectContent>
                            </Select>
                          </div>
                          <div className="flex flex-col gap-2">
                            <Label>{t("contracts.fields.pic")}</Label>

                            <ComboboxFull 
                            items={personInChargeOptions}
                            value={selectedPic}
                            onValueChange={(value) => {
                              setSelectedPic(value)
                              setContract({ 
                                ...contract, 
                                selectedPic: value
                              })
                            }}
                            placeholder={t("contracts.fields.pic")}
                            emptyText={t("bizz.noCompanies")} 
                          />
                          </div>
                          <div className="flex flex-col gap-2">
                            <Label>{t("contracts.fields.contractSignedStatus")}</Label>
                            <Input value={contract.contractSignedStatus} onChange={e => handleChange("contractSignedStatus", e.target.value)} />
                          </div>
                          <div className="flex flex-col gap-2">
                            <Label>{t("contracts.fields.contractDateCheck")}</Label>
                            <Popover>
                              <PopoverTrigger asChild>
                                <Button
                                  variant={"outline"}
                                  className={cn(
                                    "w-full justify-start text-left font-normal",
                                    !contract.contractDateCheck && "text-muted-foreground"
                                  )}
                                >
                                  <CalendarIcon className="mr-2 h-4 w-4" />
                                  {contract.contractDateCheck ? format(new Date(contract.contractDateCheck), "dd/MM/yyyy") : "Pick a date"}
                                </Button>
                              </PopoverTrigger>
                              <PopoverContent className="w-auto p-0">
                                <Calendar
                                  mode="single"
                                  selected={contract.contractDateCheck ? new Date(contract.contractDateCheck) : undefined}
                                  onSelect={(date) => {
                                    if (date) {
                                      const utcDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
                                      setContract((prev: any) => ({ ...prev, contractDateCheck: utcDate.toISOString().split('T')[0] }));
                                    }
                                  }}
                                  initialFocus
                                />
                              </PopoverContent>
                            </Popover>
                          </div>
                        </div>
                      </CardContent>
                    </Card>
                  </TabsContent>
                </div>
              </Tabs>

              <div className="flex justify-between px-4 mt-4 lg:px-6 pb-2 ">
                {isMobile ? (
                  <>
                    <Button 
                      variant="outline" 
                      onClick={handlePrevious}
                      disabled={currentTab === "contract-details"}
                      className="flex-1 mx-1"
                      type="button"
                    >
                      Previous
                    </Button>
                    <Button 
                      variant="outline"
                      onClick={handleSaveContract}
                      className="flex-1 mx-1"
                      type="submit"
                    >
                      Save
                    </Button>
                    <Button 
                      onClick={handleSend}
                      className="flex-1 mx-1"
                      type="button"
                    >
                      Send
                    </Button>
                    <Button 
                      onClick={handleNext}
                      disabled={currentTab === "execution-status"}
                      className="flex-1 mx-1"
                      type="button"
                    >
                      Next
                    </Button>
                  </>
                ) : (
                  <div className="flex gap-2">
                    <Button variant="outline" onClick={handleSaveContract}>Save Draft</Button>
                    <Button onClick={handleSend}>Send Contract</Button>
                  </div>
                )}
              </div>
            </form>
          </div>
        </div>

        {/* Alert Dialog for Broker and Bank Selection */}
        <AlertDialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
          <AlertDialogContent className="min-w-[300px] w-full max-w-[90vw] sm:max-w-md">
            <AlertDialogHeader>
              <AlertDialogTitle>Select Broker</AlertDialogTitle>
              <AlertDialogDescription>Please select the broker.</AlertDialogDescription>
            </AlertDialogHeader>

            <div className="space-y-4 py-2">
              {/* Broker Dropdown */}
              <Select onValueChange={(val) => {
                setSelectedBroker(val);
              }}>
                <SelectTrigger className="w-full">
                  <SelectValue placeholder="Select Broker" />
                </SelectTrigger>
                <SelectContent>
                  {brokers.map((broker) => (
                    <SelectItem key={broker.name} value={broker.name}>
                      {broker.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <AlertDialogFooter className="flex flex-col  sm:flex-row sm:justify-between gap-2">
              <AlertDialogCancel onClick={() => setIsDialogOpen(false)} className="w-full sm:w-auto">
                Cancel
              </AlertDialogCancel>
              <AlertDialogAction
                onClick={handleDialogConfirm}
                disabled={!selectedBroker}
                className="w-full sm:w-auto"
              >
                Confirm
              </AlertDialogAction>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>

        {/* Date Picker Dialog */}
        <AlertDialog open={isDatePickerOpen} onOpenChange={setIsDatePickerOpen}>
          <AlertDialogContent className="max-w-sm p-4">
            <AlertDialogHeader>
              <AlertDialogTitle>Selecteaza Data</AlertDialogTitle>
              <AlertDialogDescription>Selecteaza data pentru contract.</AlertDialogDescription>
            </AlertDialogHeader>
            <Calendar 
              mode="single"
              selected={new Date(contract.contractDate)} 
              onSelect={(date) => {
                if (date) {
                  handleDateChange(date);
                }
              }} 
              className="rounded-md border"
            />
            <AlertDialogFooter>
              <AlertDialogCancel onClick={() => setIsDatePickerOpen(false)}>Cancel</AlertDialogCancel>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>
      </SidebarInset>
    </SidebarProvider>
  )
}
