"use client";

import { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { FormField } from "@/components/shared/form-field";
import { CurrencyInput } from "@/components/shared/currency-input";
import { StarRating } from "@/components/shared/star-rating";
import { FileUpload } from "@/components/shared/file-upload";

const completionSchema = z.object({
  completed_at: z.string().optional(),
  actual_cost: z.number().optional(),
  notes: z.string().optional(),
  rating: z.number().min(0).max(5).optional(),
});

type CompletionFormValues = z.infer<typeof completionSchema>;

interface TaskCompletionFormProps {
  onSubmit: (data: CompletionFormValues, images: File[]) => void;
  isSubmitting?: boolean;
}

function toDateTimeLocalValue(date: Date): string {
  const y = date.getFullYear();
  const m = String(date.getMonth() + 1).padStart(2, "0");
  const d = String(date.getDate()).padStart(2, "0");
  const h = String(date.getHours()).padStart(2, "0");
  const min = String(date.getMinutes()).padStart(2, "0");
  return `${y}-${m}-${d}T${h}:${min}`;
}

export function TaskCompletionForm({
  onSubmit,
  isSubmitting,
}: TaskCompletionFormProps) {
  const [images, setImages] = useState<File[]>([]);

  const {
    register,
    handleSubmit,
    setValue,
    watch,
    formState: { errors },
  } = useForm<CompletionFormValues>({
    resolver: zodResolver(completionSchema),
    defaultValues: {
      completed_at: toDateTimeLocalValue(new Date()),
      rating: 0,
    },
  });

  const handleFormSubmit = (data: CompletionFormValues) => {
    onSubmit(data, images);
  };

  return (
    <form onSubmit={handleSubmit(handleFormSubmit)} className="space-y-6">
      <FormField
        label="Completed At"
        htmlFor="completed_at"
        error={errors.completed_at?.message}
      >
        <Input
          id="completed_at"
          type="datetime-local"
          {...register("completed_at")}
        />
      </FormField>

      <FormField
        label="Actual Cost"
        htmlFor="actual_cost"
        error={errors.actual_cost?.message}
      >
        <CurrencyInput
          value={watch("actual_cost")}
          onChange={(v) => setValue("actual_cost", v)}
        />
      </FormField>

      <FormField label="Notes" htmlFor="notes" error={errors.notes?.message}>
        <Textarea
          id="notes"
          rows={3}
          placeholder="Add notes about this completion..."
          {...register("notes")}
        />
      </FormField>

      <FormField
        label="Rating"
        htmlFor="rating"
        error={errors.rating?.message}
      >
        <StarRating
          value={watch("rating") ?? 0}
          onChange={(v) => setValue("rating", v)}
        />
      </FormField>

      <FormField label="Photos" htmlFor="photos">
        <FileUpload
          accept="image/*"
          multiple
          files={images}
          onChange={setImages}
          label="Upload completion photos"
        />
      </FormField>

      <div className="flex justify-end gap-2">
        <Button type="submit" disabled={isSubmitting}>
          {isSubmitting ? "Saving..." : "Complete Task"}
        </Button>
      </div>
    </form>
  );
}
