"use client"

import { AppSidebar } from "@/components/app-sidebar"
import { SiteHeader } from "@/components/site-header"
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar"
import { useState } from "react"
import { useTranslation } from "react-i18next"
import { Card, CardContent } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { useRouter, useSearchParams } from "next/navigation"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
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 { Calendar } from "@/components/ui/calendar"
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover"
import { format } from "date-fns"
import { IconCalendar } from "@tabler/icons-react"
import { cn } from "@/lib/utils"

interface InvoiceFormData {
  title: string;
  contractNumber: string;
  sellerCompany: string;
  buyerCompany: string;
  invoicePartner: string;
  grain: string;
  contractQuantity: string;
  executedQuantity: string;
  whoIsPayingCommission: string;
  commission: string;
  commissionCurrency: string;
  invoicedQuantity: string;
  valueCurrency: string;
  exchangeRate: string;
  valueEur: string;
  invoiceNo: string;
  invoiceDate: Date | undefined;
  invoiceDueDate: Date | undefined;
  invoiceValue: string;
  invoiceCurrency: string;
  description: string;
  eMailSubject: string;
  eMailContent: string;
}

export default function NewInvoicePage() {
  const { t } = useTranslation()
  const router = useRouter()
  const searchParams = useSearchParams()
  
  const [formData, setFormData] = useState<InvoiceFormData>({
    title: "",
    contractNumber: searchParams.get('contractNumber') || "",
    sellerCompany: searchParams.get('sellerCompany') || "",
    buyerCompany: searchParams.get('buyerCompany') || "",
    invoicePartner: "",
    grain: searchParams.get('grain') || "",
    contractQuantity: searchParams.get('quantity') || "",
    executedQuantity: "",
    whoIsPayingCommission: "",
    commission: "",
    commissionCurrency: "RON",
    invoicedQuantity: "",
    valueCurrency: "",
    exchangeRate: "",
    valueEur: "",
    invoiceNo: "",
    invoiceDate: undefined,
    invoiceDueDate: undefined,
    invoiceValue: "",
    invoiceCurrency: "RON",
    description: "",
    eMailSubject: "",
    eMailContent: "",
  })

  const handleInputChange = (field: keyof InvoiceFormData, value: string | Date | undefined) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }))
  }

  const handleSubmit = async () => {
    try {
      // Here you would typically make an API call to save the invoice
      console.log('Submitting invoice:', formData)
      router.push('/financial-operations/invoicereport')
    } catch (error) {
      console.error('Error saving invoice:', error)
    }
  }

  return (
    <SidebarProvider
      style={{
        "--sidebar-width": "calc(var(--spacing) * 72)",
        "--header-height": "calc(var(--spacing) * 12)",
      } as React.CSSProperties}
    >
      <AppSidebar variant="inset" />
      <SidebarInset>
        <SiteHeader />
        <div className="flex flex-1 flex-col">
          <div className="@container/main flex flex-1 flex-col gap-2">
            <div className="flex flex-col gap-4 py-4 md:gap-6 md:py-6">
              <div className="px-4 lg:px-6">
                <h2 className="text-2xl font-bold mb-6">{t("invoiceReport.new")}</h2>
                
                <Tabs defaultValue="general" className="w-full mb-6">
                  <TabsList className="px-4 lg:px-6 lg:w-full lg:h-14">
                    <TabsTrigger className="flex items-center gap-2 lg:text-lg" value="general">{t("invoiceReport.tabs.general")}</TabsTrigger>
                    <TabsTrigger className="flex items-center gap-2 lg:text-lg" value="details">{t("invoiceReport.tabs.details")}</TabsTrigger>
                    <TabsTrigger className="flex items-center gap-2 lg:text-lg" value="communication">{t("invoiceReport.tabs.communication")}</TabsTrigger>
                  </TabsList>

                  <Card>
                    <CardContent className="pt-6">
                      <TabsContent value="general">
                        <div className="grid grid-cols-2 gap-4">
                          <div className="space-y-2">
                            <Label htmlFor="contractNumber">{t("invoiceReport.contractNumber")}</Label>
                            <Input
                              id="contractNumber"
                              value={formData.contractNumber}
                              onChange={(e) => handleInputChange('contractNumber', e.target.value)}
                            />
                          </div>
                          <div className="space-y-2">
                            <Label htmlFor="invoiceNo">{t("invoiceReport.invoiceNumber")}</Label>
                            <Input
                              id="invoiceNo"
                              value={formData.invoiceNo}
                              onChange={(e) => handleInputChange('invoiceNo', e.target.value)}
                            />
                          </div>
                          <div className="space-y-2">
                            <Label htmlFor="sellerCompany">{t("invoiceReport.sellerCompany")}</Label>
                            <Input
                              id="sellerCompany"
                              value={formData.sellerCompany}
                              onChange={(e) => handleInputChange('sellerCompany', e.target.value)}
                            />
                          </div>
                          <div className="space-y-2">
                            <Label htmlFor="buyerCompany">{t("invoiceReport.buyerCompany")}</Label>
                            <Input
                              id="buyerCompany"
                              value={formData.buyerCompany}
                              onChange={(e) => handleInputChange('buyerCompany', e.target.value)}
                            />
                          </div>
                          <div className="space-y-2">
                            <Label htmlFor="grain">{t("invoiceReport.grain")}</Label>
                            <Input
                              id="grain"
                              value={formData.grain}
                              onChange={(e) => handleInputChange('grain', e.target.value)}
                            />
                          </div>
                          <div className="space-y-2">
                            <Label htmlFor="invoicePartner">{t("invoiceReport.invoicePartner")}</Label>
                            <Select
                              value={formData.invoicePartner}
                              onValueChange={(value) => handleInputChange('invoicePartner', value)}
                            >
                              <SelectTrigger>
                                <SelectValue placeholder="Select partner" />
                              </SelectTrigger>
                              <SelectContent>
                                <SelectItem value={formData.sellerCompany}>{formData.sellerCompany}</SelectItem>
                                <SelectItem value={formData.buyerCompany}>{formData.buyerCompany}</SelectItem>
                              </SelectContent>
                            </Select>
                          </div>
                        </div>
                      </TabsContent>

                      <TabsContent value="details">
                        <div className="grid grid-cols-2 gap-4">
                          <div className="space-y-2">
                            <Label htmlFor="contractQuantity">{t("invoiceReport.contractQuantity")}</Label>
                            <Input
                              id="contractQuantity"
                              value={formData.contractQuantity}
                              onChange={(e) => handleInputChange('contractQuantity', e.target.value)}
                            />
                          </div>
                          <div className="space-y-2">
                            <Label htmlFor="executedQuantity">{t("invoiceReport.executedQuantity")}</Label>
                            <Input
                              id="executedQuantity"
                              value={formData.executedQuantity}
                              onChange={(e) => handleInputChange('executedQuantity', e.target.value)}
                            />
                          </div>
                          <div className="space-y-2">
                            <Label htmlFor="commission">{t("invoiceReport.commission")}</Label>
                            <Input
                              id="commission"
                              value={formData.commission}
                              onChange={(e) => handleInputChange('commission', e.target.value)}
                            />
                          </div>
                          <div className="space-y-2">
                            <Label htmlFor="commissionCurrency">{t("invoiceReport.commissionCurrency")}</Label>
                            <Select
                              value={formData.commissionCurrency}
                              onValueChange={(value) => handleInputChange('commissionCurrency', value)}
                            >
                              <SelectTrigger>
                                <SelectValue placeholder="Select currency" />
                              </SelectTrigger>
                              <SelectContent>
                                <SelectItem value="RON">RON</SelectItem>
                                <SelectItem value="EUR">EUR</SelectItem>
                                <SelectItem value="USD">USD</SelectItem>
                              </SelectContent>
                            </Select>
                          </div>
                          <div className="space-y-2">
                            <Label htmlFor="invoiceValue">{t("invoiceReport.amount")}</Label>
                            <Input
                              id="invoiceValue"
                              value={formData.invoiceValue}
                              onChange={(e) => handleInputChange('invoiceValue', e.target.value)}
                            />
                          </div>
                          <div className="space-y-2">
                            <Label htmlFor="invoiceCurrency">{t("invoiceReport.invoiceCurrency")}</Label>
                            <Select
                              value={formData.invoiceCurrency}
                              onValueChange={(value) => handleInputChange('invoiceCurrency', value)}
                            >
                              <SelectTrigger>
                                <SelectValue placeholder="Select currency" />
                              </SelectTrigger>
                              <SelectContent>
                                <SelectItem value="RON">RON</SelectItem>
                                <SelectItem value="EUR">EUR</SelectItem>
                                <SelectItem value="USD">USD</SelectItem>
                              </SelectContent>
                            </Select>
                          </div>
                          <div className="space-y-2">
                            <Label htmlFor="invoiceDate">{t("invoiceReport.issueDate")}</Label>
                            <Popover>
                              <PopoverTrigger asChild>
                                <Button
                                  variant="outline"
                                  className={cn(
                                    "w-full justify-start text-left font-normal",
                                    !formData.invoiceDate && "text-muted-foreground"
                                  )}
                                >
                                  <IconCalendar className="mr-2 h-4 w-4" />
                                  {formData.invoiceDate ? format(formData.invoiceDate, "PPP") : "Select date"}
                                </Button>
                              </PopoverTrigger>
                              <PopoverContent className="w-auto p-0">
                                <Calendar
                                  mode="single"
                                  selected={formData.invoiceDate}
                                  onSelect={(date) => handleInputChange('invoiceDate', date)}
                                  initialFocus
                                />
                              </PopoverContent>
                            </Popover>
                          </div>
                          <div className="space-y-2">
                            <Label htmlFor="invoiceDueDate">{t("invoiceReport.dueDate")}</Label>
                            <Popover>
                              <PopoverTrigger asChild>
                                <Button
                                  variant="outline"
                                  className={cn(
                                    "w-full justify-start text-left font-normal",
                                    !formData.invoiceDueDate && "text-muted-foreground"
                                  )}
                                >
                                  <IconCalendar className="mr-2 h-4 w-4" />
                                  {formData.invoiceDueDate ? format(formData.invoiceDueDate, "PPP") : "Select date"}
                                </Button>
                              </PopoverTrigger>
                              <PopoverContent className="w-auto p-0">
                                <Calendar
                                  mode="single"
                                  selected={formData.invoiceDueDate}
                                  onSelect={(date) => handleInputChange('invoiceDueDate', date)}
                                  initialFocus
                                />
                              </PopoverContent>
                            </Popover>
                          </div>
                        </div>
                      </TabsContent>

                      <TabsContent value="communication">
                        <div className="grid grid-cols-1 gap-4">
                          <div className="space-y-2">
                            <Label htmlFor="eMailSubject">{t("invoiceReport.emailSubject")}</Label>
                            <Input
                              id="eMailSubject"
                              value={formData.eMailSubject}
                              onChange={(e) => handleInputChange('eMailSubject', e.target.value)}
                            />
                          </div>
                          <div className="space-y-2">
                            <Label htmlFor="eMailContent">{t("invoiceReport.emailContent")}</Label>
                            <Textarea
                              id="eMailContent"
                              value={formData.eMailContent}
                              onChange={(e) => handleInputChange('eMailContent', e.target.value)}
                              rows={6}
                            />
                          </div>
                          <div className="space-y-2">
                            <Label htmlFor="description">{t("invoiceReport.description")}</Label>
                            <Textarea
                              id="description"
                              value={formData.description}
                              onChange={(e) => handleInputChange('description', e.target.value)}
                              rows={4}
                            />
                          </div>
                        </div>
                      </TabsContent>

                      <div className="flex justify-end gap-4 mt-6">
                        <Button variant="outline" onClick={() => router.back()}>
                          {t("common.cancel")}
                        </Button>
                        <Button onClick={handleSubmit}>
                          {t("common.save")}
                        </Button>
                      </div>
                    </CardContent>
                  </Card>
                </Tabs>
              </div>
            </div>
          </div>
        </div>
      </SidebarInset>
    </SidebarProvider>
  )
}
