"use client"

import * as React from "react"
import { useRouter } from "next/navigation"
import { useTransition } from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Pencil, Save, X } from "lucide-react"
import { getBiddingConditions, updateBiddingConditions } from "@/lib/bidding/service"
import { getIncotermsForSelection, getPaymentTermsForSelection, getPlaceOfShippingForSelection, getPlaceOfDestinationForSelection } from "@/lib/procurement-select/service"
import { useToast } from "@/hooks/use-toast"

interface BiddingConditionsEditProps {
  biddingId: number
  initialConditions?: any | null
}

export function BiddingConditionsEdit({ biddingId, initialConditions }: BiddingConditionsEditProps) {
  const router = useRouter()
  const { toast } = useToast()
  const [isPending, startTransition] = useTransition()
  const [isEditing, setIsEditing] = React.useState(false)

  // Procurement 데이터 상태들
  const [paymentTermsOptions, setPaymentTermsOptions] = React.useState<Array<{code: string, description: string}>>([])
  const [incotermsOptions, setIncotermsOptions] = React.useState<Array<{code: string, description: string}>>([])
  const [shippingPlaces, setShippingPlaces] = React.useState<Array<{code: string, description: string}>>([])
  const [destinationPlaces, setDestinationPlaces] = React.useState<Array<{code: string, description: string}>>([])
  const [procurementLoading, setProcurementLoading] = React.useState(false)

  const [conditions, setConditions] = React.useState({
    paymentTerms: initialConditions?.paymentTerms || "",
    taxConditions: initialConditions?.taxConditions || "",
    incoterms: initialConditions?.incoterms || "",
    contractDeliveryDate: initialConditions?.contractDeliveryDate
      ? new Date(initialConditions.contractDeliveryDate).toISOString().split('T')[0]
      : "",
    shippingPort: initialConditions?.shippingPort || "",
    destinationPort: initialConditions?.destinationPort || "",
    isPriceAdjustmentApplicable: initialConditions?.isPriceAdjustmentApplicable || false,
    sparePartOptions: initialConditions?.sparePartOptions || "",
  })


  const handleSave = () => {
    startTransition(async () => {
      try {
        const result = await updateBiddingConditions(biddingId, conditions)
        
        if (result.success) {
          toast({
            title: "성공",
            description: (result as { success: true; message: string }).message,
            variant: "default",
          })
          setIsEditing(false)
          router.refresh()
        } else {
          toast({
            title: "오류",
            description: (result as { success: false; error: string }).error || "입찰 조건 업데이트 중 오류가 발생했습니다.",
            variant: "destructive",
          })
        }
      } catch (error) {
        console.error('Error updating bidding conditions:', error)
        toast({
          title: "오류",
          description: "입찰 조건 업데이트 중 오류가 발생했습니다.",
          variant: "destructive",
        })
      }
    })
  }

  // Procurement 데이터 로드 함수들
  const loadPaymentTerms = React.useCallback(async () => {
    setProcurementLoading(true);
    try {
      const data = await getPaymentTermsForSelection();
      setPaymentTermsOptions(data);
    } catch (error) {
      console.error("Failed to load payment terms:", error);
      toast({
        title: "오류",
        description: "결제조건 목록을 불러오는데 실패했습니다.",
        variant: "destructive",
      })
    } finally {
      setProcurementLoading(false);
    }
  }, [toast]);

  const loadIncoterms = React.useCallback(async () => {
    setProcurementLoading(true);
    try {
      const data = await getIncotermsForSelection();
      setIncotermsOptions(data);
    } catch (error) {
      console.error("Failed to load incoterms:", error);
      toast({
        title: "오류",
        description: "운송조건 목록을 불러오는데 실패했습니다.",
        variant: "destructive",
      })
    } finally {
      setProcurementLoading(false);
    }
  }, [toast]);

  const loadShippingPlaces = React.useCallback(async () => {
    setProcurementLoading(true);
    try {
      const data = await getPlaceOfShippingForSelection();
      setShippingPlaces(data);
    } catch (error) {
      console.error("Failed to load shipping places:", error);
      toast({
        title: "오류",
        description: "선적지 목록을 불러오는데 실패했습니다.",
        variant: "destructive",
      })
    } finally {
      setProcurementLoading(false);
    }
  }, [toast]);

  const loadDestinationPlaces = React.useCallback(async () => {
    setProcurementLoading(true);
    try {
      const data = await getPlaceOfDestinationForSelection();
      setDestinationPlaces(data);
    } catch (error) {
      console.error("Failed to load destination places:", error);
      toast({
        title: "오류",
        description: "하역지 목록을 불러오는데 실패했습니다.",
        variant: "destructive",
      })
    } finally {
      setProcurementLoading(false);
    }
  }, [toast]);

  // 편집 모드로 전환할 때 procurement 데이터 로드
  React.useEffect(() => {
    if (isEditing) {
      loadPaymentTerms();
      loadIncoterms();
      loadShippingPlaces();
      loadDestinationPlaces();
    }
  }, [isEditing, loadPaymentTerms, loadIncoterms, loadShippingPlaces, loadDestinationPlaces]);

  const handleCancel = () => {
    setConditions({
      paymentTerms: initialConditions?.paymentTerms || "",
      taxConditions: initialConditions?.taxConditions || "",
      incoterms: initialConditions?.incoterms || "",
      contractDeliveryDate: initialConditions?.contractDeliveryDate
        ? new Date(initialConditions.contractDeliveryDate).toISOString().split('T')[0]
        : "",
      shippingPort: initialConditions?.shippingPort || "",
      destinationPort: initialConditions?.destinationPort || "",
      isPriceAdjustmentApplicable: initialConditions?.isPriceAdjustmentApplicable || false,
      sparePartOptions: initialConditions?.sparePartOptions || "",
    })
    setIsEditing(false)
  }

  if (!isEditing) {
    return (
      <Card className="mt-6">
        <CardHeader className="flex flex-row items-center justify-between">
          <CardTitle>입찰 조건</CardTitle>
          <Button
            variant="outline"
            size="sm"
            onClick={() => setIsEditing(true)}
            className="flex items-center gap-2"
          >
            <Pencil className="w-4 h-4" />
            수정
          </Button>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 text-sm">
            <div>
              <Label className="text-muted-foreground">지급조건</Label>
              <p className="font-medium">
                {conditions.paymentTerms
                  ? paymentTermsOptions.find(opt => opt.code === conditions.paymentTerms)?.code || conditions.paymentTerms
                  : "미설정"
                }
              </p>
            </div>
            <div>
              <Label className="text-muted-foreground">세금조건</Label>
              <p className="font-medium">{conditions.taxConditions || "미설정"}</p>
            </div>
            <div>
              <Label className="text-muted-foreground">운송조건</Label>
              <p className="font-medium">
                {conditions.incoterms
                  ? incotermsOptions.find(opt => opt.code === conditions.incoterms)?.code || conditions.incoterms
                  : "미설정"
                }
              </p>
            </div>
            <div>
              <Label className="text-muted-foreground">계약 납품일</Label>
              <p className="font-medium">
                {conditions.contractDeliveryDate 
                  ? new Date(conditions.contractDeliveryDate).toLocaleDateString('ko-KR')
                  : "미설정"
                }
              </p>
            </div>
            <div>
              <Label className="text-muted-foreground">선적지</Label>
              <p className="font-medium">{conditions.shippingPort || "미설정"}</p>
            </div>
            <div>
              <Label className="text-muted-foreground">하역지</Label>
              <p className="font-medium">{conditions.destinationPort || "미설정"}</p>
            </div>
            <div>
              <Label className="text-muted-foreground">연동제 적용</Label>
              <p className="font-medium">{conditions.isPriceAdjustmentApplicable ? "적용 가능" : "적용 불가"}</p>
            </div>
              <div>
                <Label className="text-muted-foreground">스페어파트 옵션</Label>
                <p className="font-medium">{conditions.sparePartOptions}</p>
              </div>

          </div>
        </CardContent>
      </Card>
    )
  }

  return (
    <Card className="mt-6">
      <CardHeader className="flex flex-row items-center justify-between">
        <CardTitle>입찰 조건 수정</CardTitle>
        <div className="flex items-center gap-2">
          <Button
            variant="outline"
            size="sm"
            onClick={handleCancel}
            disabled={isPending}
            className="flex items-center gap-2"
          >
            <X className="w-4 h-4" />
            취소
          </Button>
          <Button
            size="sm"
            onClick={handleSave}
            disabled={isPending}
            className="flex items-center gap-2"
          >
            <Save className="w-4 h-4" />
            저장
          </Button>
        </div>
      </CardHeader>
      <CardContent className="space-y-6">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div className="space-y-2">
            <Label htmlFor="paymentTerms">지급조건 *</Label>
            <Select
              value={conditions.paymentTerms}
              onValueChange={(value) => setConditions(prev => ({
                ...prev,
                paymentTerms: value
              }))}
            >
              <SelectTrigger>
                <SelectValue placeholder="지급조건 선택" />
              </SelectTrigger>
              <SelectContent>
                {paymentTermsOptions.length > 0 ? (
                  paymentTermsOptions.map((option) => (
                    <SelectItem key={option.code} value={option.code}>
                      {option.code} {option.description && `(${option.description})`}
                    </SelectItem>
                  ))
                ) : (
                  <SelectItem value="loading" disabled>
                    데이터를 불러오는 중...
                  </SelectItem>
                )}
              </SelectContent>
            </Select>
          </div>

          <div className="space-y-2">
            <Label htmlFor="taxConditions">세금조건 *</Label>
            <Input
              id="taxConditions"
              placeholder="예: VAT 별도, 원천세 3.3%"
              value={conditions.taxConditions}
              onChange={(e) => setConditions(prev => ({
                ...prev,
                taxConditions: e.target.value
              }))}
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="incoterms">운송조건(인코텀즈) *</Label>
            <Select
              value={conditions.incoterms}
              onValueChange={(value) => setConditions(prev => ({
                ...prev,
                incoterms: value
              }))}
            >
              <SelectTrigger>
                <SelectValue placeholder="인코텀즈 선택" />
              </SelectTrigger>
              <SelectContent>
                {incotermsOptions.length > 0 ? (
                  incotermsOptions.map((option) => (
                    <SelectItem key={option.code} value={option.code}>
                      {option.code} {option.description && `(${option.description})`}
                    </SelectItem>
                  ))
                ) : (
                  <SelectItem value="loading" disabled>
                    데이터를 불러오는 중...
                  </SelectItem>
                )}
              </SelectContent>
            </Select>
          </div>

          <div className="space-y-2">
            <Label htmlFor="contractDeliveryDate">계약 납품일</Label>
            <Input
              id="contractDeliveryDate"
              type="date"
              value={conditions.contractDeliveryDate}
              onChange={(e) => setConditions(prev => ({
                ...prev,
                contractDeliveryDate: e.target.value
              }))}
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="shippingPort">선적지</Label>
            <Select
              value={conditions.shippingPort}
              onValueChange={(value) => setConditions(prev => ({
                ...prev,
                shippingPort: value
              }))}
            >
              <SelectTrigger>
                <SelectValue placeholder="선적지 선택" />
              </SelectTrigger>
              <SelectContent>
                {shippingPlaces.length > 0 ? (
                  shippingPlaces.map((place) => (
                    <SelectItem key={place.code} value={place.code}>
                      {place.code} {place.description && `(${place.description})`}
                    </SelectItem>
                  ))
                ) : (
                  <SelectItem value="loading" disabled>
                    데이터를 불러오는 중...
                  </SelectItem>
                )}
              </SelectContent>
            </Select>
          </div>

          <div className="space-y-2">
            <Label htmlFor="destinationPort">하역지</Label>
            <Select
              value={conditions.destinationPort}
              onValueChange={(value) => setConditions(prev => ({
                ...prev,
                destinationPort: value
              }))}
            >
              <SelectTrigger>
                <SelectValue placeholder="하역지 선택" />
              </SelectTrigger>
              <SelectContent>
                {destinationPlaces.length > 0 ? (
                  destinationPlaces.map((place) => (
                    <SelectItem key={place.code} value={place.code}>
                      {place.code} {place.description && `(${place.description})`}
                    </SelectItem>
                  ))
                ) : (
                  <SelectItem value="loading" disabled>
                    데이터를 불러오는 중...
                  </SelectItem>
                )}
              </SelectContent>
            </Select>
          </div>
        </div>

        <div className="flex items-center space-x-2">
          <Switch
            id="isPriceAdjustmentApplicable"
            checked={conditions.isPriceAdjustmentApplicable}
            onCheckedChange={(checked) => setConditions(prev => ({
              ...prev,
              isPriceAdjustmentApplicable: checked
            }))}
          />
          <Label htmlFor="isPriceAdjustmentApplicable">연동제 적용 가능</Label>
        </div>

        <div className="space-y-2">
          <Label htmlFor="sparePartOptions">스페어파트 옵션</Label>
          <Textarea
            id="sparePartOptions"
            placeholder="스페어파트 관련 옵션을 입력하세요"
            value={conditions.sparePartOptions}
            onChange={(e) => setConditions(prev => ({
              ...prev,
              sparePartOptions: e.target.value
            }))}
            rows={3}
          />
        </div>
      </CardContent>
    </Card>
  )
}
