"use client"

import { AppSidebar } from "@/components/app-sidebar"
import { SiteHeader } from "@/components/site-header"
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar"
import { useRouter } from "next/navigation"
import { useState, useEffect } from "react"
import { Button } from "@/components/ui/button"
import { Card, CardTitle, CardHeader, CardContent } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"

interface NoticeSetting {
  partnerName: string;
  series: string;
  vatNo: string;
  regCom: string;
  address: string;
  county: string;
  numberFrom: number;
  numberTo: number;
}

interface Notice {
  id: number;
  contractNumber: string;
  seller: string;
  buyer: string;
  product: string;
  origin: string;
  harvestYear: string;
  series: string;
  noticeNumber: string;
  noticeDate: string;
  grossQuantity: string;
  netQuantity: string;
  tareQuantity: string;
  licensePlate: string;
  driverName: string;
  driverCI: string;
  placeLoading: string;
  placeUnloading: string;
  uitCode: string;
  uitCodeFull: string;
  mentions: string;
}

export default function NewNoticePage() {
  const router = useRouter()
  const [settings, setSettings] = useState<NoticeSetting[]>([])
  const [selectedSetting, setSelectedSetting] = useState<NoticeSetting | null>(null)
  const [notice, setNotice] = useState<Notice>({
    id: 0,
    contractNumber: "",
    seller: "",
    buyer: "",
    product: "",
    origin: "",
    harvestYear: "",
    series: "",
    noticeNumber: "",
    noticeDate: new Date().toISOString().slice(0, 10),
    grossQuantity: "",
    netQuantity: "",
    tareQuantity: "",
    licensePlate: "",
    driverName: "",
    driverCI: "",
    placeLoading: "",
    placeUnloading: "",
    uitCode: "",
    uitCodeFull: "",
    mentions: ""
  })
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)

  // Calculate tare quantity when gross or net quantity changes
  useEffect(() => {
    if (notice.grossQuantity && notice.netQuantity) {
      const gross = parseFloat(notice.grossQuantity);
      const net = parseFloat(notice.netQuantity);
      if (!isNaN(gross) && !isNaN(net)) {
        setNotice(prev => ({
          ...prev,
          tareQuantity: (gross - net).toFixed(3)
        }));
      }
    }
  }, [notice.grossQuantity, notice.netQuantity]);

  useEffect(() => {
    fetch("/api/execution-operations/notice")
      .then(res => res.json())
      .then(data => {
        setSettings(data);
        setLoading(false);
      })
      .catch(error => {
        console.error("Error loading settings:", error);
        setLoading(false);
      });
  }, [])

  const handleSettingSelect = (val: string) => {
    const setting = settings.find(s => s.partnerName === val);
    if (setting) {
      setSelectedSetting(setting);
      setNotice({
        ...notice,
        seller: setting.partnerName,
        series: setting.series,
        noticeNumber: setting.numberFrom.toString(),
        contractNumber: `CNT-${setting.series}-${setting.numberFrom}`
      });
    }
  }

  const handleSave = (action: string) => {
    setSaving(true);
    // Here you would typically make an API call to save the notice
    setTimeout(() => {
      alert(`Notice saved! (${action}) (Simulated)`);
      setSaving(false);
      router.push("/execution-operations/notice");
    }, 1000);
  }

  if (loading) return <div>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="New Notice" />
        <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">
              <h2 className="text-2xl font-bold">New Notice</h2>
            </div>
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 px-4 lg:px-6">
              <Card>
                <CardHeader>
                  <CardTitle>Notice Details</CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="mb-4">
                    <Select value={selectedSetting?.partnerName || ""} onValueChange={handleSettingSelect}>
                      <SelectTrigger><SelectValue placeholder="Select company" /></SelectTrigger>
                      <SelectContent>
                        {settings.map(setting => (
                          <SelectItem key={setting.partnerName} value={setting.partnerName}>
                            {setting.partnerName}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div className="flex flex-col gap-2">
                      <span className="font-medium">Contract Number</span>
                      <Input value={notice.contractNumber} readOnly />
                    </div>
                    <div className="flex flex-col gap-2">
                      <span className="font-medium">Seller</span>
                      <Input value={notice.seller} readOnly />
                    </div>
                    <div className="flex flex-col gap-2">
                      <span className="font-medium">Buyer</span>
                      <Input value={notice.buyer} readOnly />
                    </div>
                    <div className="flex flex-col gap-2">
                      <span className="font-medium">Product</span>
                      <Input value={notice.product} readOnly />
                    </div>
                    <div className="flex flex-col gap-2">
                      <span className="font-medium">Origin</span>
                      <Input value={notice.origin} readOnly />
                    </div>
                    <div className="flex flex-col gap-2">
                      <span className="font-medium">Harvest Year</span>
                      <Input value={notice.harvestYear} readOnly />
                    </div>
                    <div className="flex flex-col gap-2">
                      <span className="font-medium">Series</span>
                      <Input value={notice.series} readOnly />
                    </div>
                    <div className="flex flex-col gap-2">
                      <span className="font-medium">Notice Number</span>
                      <Input value={notice.noticeNumber} readOnly />
                    </div>
                    <div className="flex flex-col gap-2">
                      <span className="font-medium">Date Notice</span>
                      <Input type="date" value={notice.noticeDate} onChange={e => setNotice({ ...notice, noticeDate: e.target.value })} />
                    </div>
                    <div className="flex flex-col gap-2">
                      <span className="font-medium">Gross Quantity</span>
                      <Input type="number" step="0.001" value={notice.grossQuantity} onChange={e => setNotice({ ...notice, grossQuantity: e.target.value })} />
                    </div>
                    <div className="flex flex-col gap-2">
                      <span className="font-medium">Net Quantity</span>
                      <Input type="number" step="0.001" value={notice.netQuantity} onChange={e => setNotice({ ...notice, netQuantity: e.target.value })} />
                    </div>
                    <div className="flex flex-col gap-2">
                      <span className="font-medium">Tare Quantity</span>
                      <Input type="number" step="0.001" value={notice.tareQuantity} readOnly />
                    </div>
                    <div className="flex flex-col gap-2">
                      <span className="font-medium">License Plate</span>
                      <Input value={notice.licensePlate} onChange={e => setNotice({ ...notice, licensePlate: e.target.value })} />
                    </div>
                    <div className="flex flex-col gap-2">
                      <span className="font-medium">Driver Name</span>
                      <Input value={notice.driverName} onChange={e => setNotice({ ...notice, driverName: e.target.value })} />
                    </div>
                    <div className="flex flex-col gap-2">
                      <span className="font-medium">Driver ID</span>
                      <Input value={notice.driverCI} onChange={e => setNotice({ ...notice, driverCI: e.target.value })} />
                    </div>
                    <div className="flex flex-col gap-2">
                      <span className="font-medium">Loading Place</span>
                      <Input value={notice.placeLoading} onChange={e => setNotice({ ...notice, placeLoading: e.target.value })} />
                    </div>
                    <div className="flex flex-col gap-2">
                      <span className="font-medium">Unloading Place</span>
                      <Input value={notice.placeUnloading} onChange={e => setNotice({ ...notice, placeUnloading: e.target.value })} />
                    </div>
                    <div className="flex flex-col gap-2">
                      <span className="font-medium">UIT Code</span>
                      <Input value={notice.uitCode} onChange={e => setNotice({ ...notice, uitCode: e.target.value })} />
                    </div>
                    <div className="flex flex-col gap-2">
                      <span className="font-medium">Full UIT Code</span>
                      <Input value={notice.uitCodeFull} onChange={e => setNotice({ ...notice, uitCodeFull: e.target.value })} />
                    </div>
                    <div className="flex flex-col gap-2 col-span-2">
                      <span className="font-medium">Additional Mentions</span>
                      <Input value={notice.mentions} onChange={e => setNotice({ ...notice, mentions: e.target.value })} />
                    </div>
                  </div>
                </CardContent>
              </Card>
            </div>
            <div className="flex gap-4 justify-end px-4 lg:px-6">
              <Button onClick={() => handleSave("save")} disabled={saving}>Save</Button>
              <Button onClick={() => handleSave("save-generate")} disabled={saving}>Save & Generate</Button>
              <Button onClick={() => handleSave("save-send")} disabled={saving}>Save & Send to Buyer</Button>
            </div>
          </div>
        </div>
      </SidebarInset>
    </SidebarProvider>
  )
} 