"use client"

import { useState } from "react"
import { useForm } from "react-hook-form"
import { CalendarIcon } from "lucide-react"
import { format } from "date-fns"

import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetHeader,
  SheetTitle,
} from "@/components/ui/sheet"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Calendar } from "@/components/ui/calendar"
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover"
import { cn } from "@/lib/utils"

interface PaymentFormData {
  paymentDate: Date
  amountPaid: string
  notes: string
}

interface RecordPaymentSheetProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  onSubmit: (data: PaymentFormData) => void
  cpCompanyName: string
}

export function RecordPaymentSheet({ 
  open, 
  onOpenChange, 
  onSubmit,
  cpCompanyName 
}: RecordPaymentSheetProps) {
  const { register, handleSubmit, formState: { errors }, reset, setValue, watch } = useForm<PaymentFormData>({
    defaultValues: {
      paymentDate: new Date(),
      amountPaid: "",
      notes: "",
    }
  })

  const [calendarOpen, setCalendarOpen] = useState(false)
  const paymentDate = watch("paymentDate")

  const onFormSubmit = (data: PaymentFormData) => {
    onSubmit(data)
    handleClose()
  }

  const handleClose = () => {
    onOpenChange(false)
    reset({
      paymentDate: new Date(),
      amountPaid: "",
      notes: "",
    })
  }

  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent className="sm:max-w-[500px] flex flex-col p-0">
        <SheetHeader className="px-6 py-4 border-b sticky top-0 bg-background z-10">
          <SheetTitle>Record a Payment</SheetTitle>
          <SheetDescription>
            Record commission payment for {cpCompanyName}. System will automatically adjust against oldest pending bookings (FIFO).
          </SheetDescription>
        </SheetHeader>

        <div className="flex-1 overflow-y-auto px-6 py-6">
          <form id="record-payment-form" onSubmit={handleSubmit(onFormSubmit)} className="space-y-6">
            {/* Payment Date */}
            <div className="space-y-2">
              <Label htmlFor="paymentDate">Payment Date *</Label>
              <Popover open={calendarOpen} onOpenChange={setCalendarOpen}>
                <PopoverTrigger asChild>
                  <Button
                    variant="outline"
                    className={cn(
                      "w-full justify-start text-left font-normal",
                      !paymentDate && "text-muted-foreground"
                    )}
                  >
                    <CalendarIcon className="mr-2 h-4 w-4" />
                    {paymentDate ? format(paymentDate, "dd MMM yyyy") : "Select date"}
                  </Button>
                </PopoverTrigger>
                <PopoverContent className="w-auto p-0" align="start">
                  <Calendar
                    mode="single"
                    selected={paymentDate}
                    onSelect={(date) => {
                      setValue("paymentDate", date || new Date())
                      setCalendarOpen(false)
                    }}
                    initialFocus
                  />
                </PopoverContent>
              </Popover>
            </div>

            {/* Amount Paid */}
            <div className="space-y-2">
              <Label htmlFor="amountPaid">Amount Paid *</Label>
              <Input
                id="amountPaid"
                {...register("amountPaid", { required: "Amount is required" })}
                placeholder="e.g., 200000 or 2,00,000"
              />
              {errors.amountPaid && (
                <p className="text-sm text-destructive">{errors.amountPaid.message}</p>
              )}
              <p className="text-xs text-muted-foreground">
                Enter amount in numbers. System will auto-adjust against oldest pending commissions (FIFO).
              </p>
            </div>

            {/* Notes */}
            <div className="space-y-2">
              <Label htmlFor="notes">Notes</Label>
              <Textarea
                id="notes"
                {...register("notes")}
                placeholder="Additional notes about this payment..."
                rows={3}
              />
            </div>

            {/* FIFO Logic Explanation */}
            <div className="p-4 bg-muted rounded-lg">
              <h4 className="text-sm font-semibold mb-2">Auto-Adjustment Logic (FIFO)</h4>
              <ul className="text-xs text-muted-foreground space-y-1">
                <li>• Oldest pending commission gets cleared first</li>
                <li>• If amount remains, moves to next booking</li>
                <li>• Continues until payment amount is exhausted</li>
                <li>• Updates all affected bookings automatically</li>
              </ul>
            </div>
          </form>
        </div>

        <div className="px-6 py-4 border-t sticky bottom-0 bg-background flex justify-end gap-2">
          <Button type="button" variant="outline" onClick={handleClose}>
            Cancel
          </Button>
          <Button type="submit" form="record-payment-form">
            Record Payment
          </Button>
        </div>
      </SheetContent>
    </Sheet>
  )
}
