"use client";

import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
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 { QuillEditorSkeleton } from "@/components/shared/skeletons";
import { RichTextEditor } from "@/components/shared/rich-text-editor";
import { FIX_PACKAGES_ADMIN } from "@/lib/strings";
import type { FixPackageInput } from "@/lib/validations/fix-packages";
import { CalendarIcon } from "lucide-react";
import { addDays, format, startOfDay } from "date-fns";
import { Calendar } from "@/components/ui/calendar";
import { cn } from "@/lib/utils";
import type {
  FieldErrors,
  UseFormRegister,
  UseFormSetValue,
  UseFormWatch,
} from "react-hook-form";

export interface PackageInfoCardProps {
  register: UseFormRegister<FixPackageInput>;
  errors: FieldErrors<FixPackageInput>;
  watch: UseFormWatch<FixPackageInput>;
  setValue: UseFormSetValue<FixPackageInput>;
  isDataLoaded: boolean;
}

export function PackageInfoCard({
  register,
  errors,
  watch,
  setValue,
  isDataLoaded,
}: PackageInfoCardProps) {
  const watchStatus = watch("status");
  const watchPackageType = watch("package_type");
  const watchPackageCategory = watch("package_category");

  const today = startOfDay(new Date());
  const tomorrow = addDays(today, 1);

  return (
    <Card>
      <CardHeader className="flex flex-row items-start justify-between gap-6">
        <div>
          <CardTitle>{FIX_PACKAGES_ADMIN.PACKAGE_INFORMATION}</CardTitle>
          <CardDescription>
            {FIX_PACKAGES_ADMIN.PACKAGE_INFORMATION_DESCRIPTION}
          </CardDescription>
        </div>
        <div className="flex items-center gap-3 flex-shrink-0">
          <div className="grid gap-1">
            <Label htmlFor="sort" className="text-xs">
              {FIX_PACKAGES_ADMIN.SORT_LABEL}
            </Label>
            <Input
              id="sort"
              type="number"
              min={1}
              step={1}
              placeholder={FIX_PACKAGES_ADMIN.SORT_PLACEHOLDER}
              {...register("sort", {
                setValueAs: (value) => (value === "" ? null : Number(value)),
              })}
              aria-invalid={!!errors.sort}
              className="w-24 h-8 text-xs"
            />
            {errors.sort && (
              <p className="text-xs text-destructive">{errors.sort.message}</p>
            )}
          </div>
          <div className="grid gap-1">
            <Label className="text-xs">{FIX_PACKAGES_ADMIN.STATUS_LABEL}</Label>
            <Select
              value={watchStatus}
              onValueChange={(val: "active" | "inactive") =>
                setValue("status", val)
              }
            >
              <SelectTrigger className="w-32 h-8 text-xs">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="active">
                  {FIX_PACKAGES_ADMIN.ACTIVE}
                </SelectItem>
                <SelectItem value="inactive">
                  {FIX_PACKAGES_ADMIN.INACTIVE}
                </SelectItem>
              </SelectContent>
            </Select>
          </div>
          <div className="grid gap-1">
            <Label className="text-xs">
              {FIX_PACKAGES_ADMIN.PACKAGE_TYPE_LABEL}
            </Label>
            <Select
              value={watchPackageType}
              onValueChange={(val: "normal" | "premium") =>
                setValue("package_type", val)
              }
            >
              <SelectTrigger className="w-32 h-8 text-xs">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="normal">
                  {FIX_PACKAGES_ADMIN.NORMAL}
                </SelectItem>
                <SelectItem value="premium">
                  {FIX_PACKAGES_ADMIN.PREMIUM}
                </SelectItem>
              </SelectContent>
            </Select>
          </div>
          <div className="grid gap-1">
            <Label className="text-xs">Package Category</Label>
            <Select
              value={watchPackageCategory}
              onValueChange={(
                val: "fix_package" | "spiritual" | "honeymoon"
              ) => setValue("package_category", val)}
            >
              <SelectTrigger className="w-36 h-8 text-xs">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="fix_package">Fix Package</SelectItem>
                <SelectItem value="spiritual">Spiritual</SelectItem>
                <SelectItem value="honeymoon">Honeymoon</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </div>
      </CardHeader>
      <CardContent className="space-y-4">
        <div className="grid gap-2">
          <Label htmlFor="package-name">
            {FIX_PACKAGES_ADMIN.PACKAGE_NAME}
          </Label>
          <Input
            id="package-name"
            placeholder={FIX_PACKAGES_ADMIN.PACKAGE_NAME_PLACEHOLDER}
            {...register("name")}
            aria-invalid={!!errors.name}
          />
          {errors.name && (
            <p className="text-sm text-destructive">{errors.name.message}</p>
          )}
        </div>
        <div className="grid gap-2">
          <Label htmlFor="location-detail">
            {FIX_PACKAGES_ADMIN.LOCATION_DETAILS_LABEL}
          </Label>
          <Textarea
            id="location-detail"
            placeholder={FIX_PACKAGES_ADMIN.LOCATION_DETAILS_PLACEHOLDER}
            rows={2}
            {...register("location_detail")}
            aria-invalid={!!errors.location_detail}
          />
          {errors.location_detail && (
            <p className="text-sm text-destructive">
              {errors.location_detail.message}
            </p>
          )}
        </div>
        <div className="grid grid-cols-3 gap-4">
          <div className="grid gap-2">
            <Label>{FIX_PACKAGES_ADMIN.START_DATE_LABEL}</Label>
            <Popover>
              <PopoverTrigger asChild>
                <Button
                  variant="outline"
                  className={cn(
                    "w-full justify-start text-left font-normal",
                    !watch("start_date") && "text-muted-foreground"
                  )}
                >
                  <CalendarIcon className="mr-2 h-4 w-4" />
                  {watch("start_date") ? (
                    format(new Date(watch("start_date")!), "PPP")
                  ) : (
                    <span>{FIX_PACKAGES_ADMIN.PICK_START_DATE}</span>
                  )}
                </Button>
              </PopoverTrigger>
              <PopoverContent className="w-auto p-0 z-100" align="start">
                <Calendar
                  mode="single"
                  selected={
                    watch("start_date")
                      ? new Date(watch("start_date")!)
                      : undefined
                  }
                  onSelect={(date) =>
                    setValue(
                      "start_date",
                      date ? format(date, "yyyy-MM-dd") : "",
                      { shouldValidate: true }
                    )
                  }
                  disabled={(date) => date < today}
                  initialFocus
                />
              </PopoverContent>
            </Popover>
            {errors.start_date && (
              <p className="text-sm text-destructive">
                {errors.start_date.message}
              </p>
            )}
          </div>
          <div className="grid gap-2">
            <Label>{FIX_PACKAGES_ADMIN.END_DATE_LABEL}</Label>
            <Popover>
              <PopoverTrigger asChild>
                <Button
                  variant="outline"
                  className={cn(
                    "w-full justify-start text-left font-normal",
                    !watch("end_date") && "text-muted-foreground"
                  )}
                >
                  <CalendarIcon className="mr-2 h-4 w-4" />
                  {watch("end_date") ? (
                    format(new Date(watch("end_date")), "PPP")
                  ) : (
                    <span>{FIX_PACKAGES_ADMIN.PICK_END_DATE}</span>
                  )}
                </Button>
              </PopoverTrigger>
              <PopoverContent className="w-auto p-0 z-100" align="start">
                <Calendar
                  mode="single"
                  selected={
                    watch("end_date") ? new Date(watch("end_date")) : undefined
                  }
                  onSelect={(date) =>
                    setValue(
                      "end_date",
                      date ? format(date, "yyyy-MM-dd") : "",
                      { shouldValidate: true }
                    )
                  }
                  disabled={(date) => date < tomorrow}
                  initialFocus
                />
              </PopoverContent>
            </Popover>
            {errors.end_date && (
              <p className="text-sm text-destructive">
                {errors.end_date.message}
              </p>
            )}
          </div>
          <div className="grid gap-2">
            <Label htmlFor="price">{FIX_PACKAGES_ADMIN.PRICE_LABEL}</Label>
            <Input
              id="price"
              type="number"
              placeholder={FIX_PACKAGES_ADMIN.PRICE_PLACEHOLDER}
              {...register("price", { valueAsNumber: true })}
              aria-invalid={!!errors.price}
            />
            {errors.price && (
              <p className="text-sm text-destructive">{errors.price.message}</p>
            )}
          </div>
          <div className="grid gap-2">
            <Label htmlFor="discount_price">
              {FIX_PACKAGES_ADMIN.DISCOUNT_PRICE_LABEL}
            </Label>
            <div className="relative">
              <Input
                id="discount_price"
                type="number"
                placeholder={FIX_PACKAGES_ADMIN.DISCOUNT_PLACEHOLDER}
                {...register("discount_price", { valueAsNumber: true })}
                aria-invalid={!!errors.discount_price}
              />
              {watch("price") > 0 &&
                (watch("discount_price") || 0) > 0 &&
                watch("price") > (watch("discount_price") || 0) && (
                  <div className="absolute right-3 top-1/2 -translate-y-1/2 text-xs font-medium text-green-600 bg-green-50 px-2 py-0.5 rounded-full border border-green-200">
                    {Math.round(
                      ((watch("price") - (watch("discount_price") || 0)) /
                        watch("price")) *
                        100
                    )}
                    % OFF
                  </div>
                )}
            </div>
            {errors.discount_price && (
              <p className="text-sm text-destructive">
                {errors.discount_price.message}
              </p>
            )}
          </div>
        </div>
        <div className="grid grid-cols-2 gap-4">
          <div className="grid gap-2">
            <Label htmlFor="inclusions">
              {FIX_PACKAGES_ADMIN.INCLUSIONS_LABEL}
            </Label>
            {isDataLoaded ? (
              <RichTextEditor
                value={(watch("inclusion") as string) || ""}
                onChange={(value: string) =>
                  setValue("inclusion" as keyof FixPackageInput, value)
                }
                placeholder={FIX_PACKAGES_ADMIN.INCLUSIONS_PLACEHOLDER}
              />
            ) : (
              <QuillEditorSkeleton />
            )}
          </div>
          <div className="grid gap-2">
            <Label htmlFor="exclusions">
              {FIX_PACKAGES_ADMIN.EXCLUSIONS_LABEL}
            </Label>
            {isDataLoaded ? (
              <RichTextEditor
                value={(watch("exclusion") as string) || ""}
                onChange={(value: string) =>
                  setValue("exclusion" as keyof FixPackageInput, value)
                }
                placeholder={FIX_PACKAGES_ADMIN.EXCLUSIONS_PLACEHOLDER}
              />
            ) : (
              <QuillEditorSkeleton />
            )}
          </div>
        </div>
      </CardContent>
    </Card>
  );
}
