"use client";

import { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Loader2 } from "lucide-react";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { FormField } from "@/components/shared/form-field";
import { LookupSelect } from "@/components/shared/lookup-select";
import { FileUpload } from "@/components/shared/file-upload";
import { CurrencyInput } from "@/components/shared/currency-input";
import { useResidences } from "@/lib/hooks/use-residences";
import type { DocumentResponse, DocumentType } from "@/lib/api/documents";

// ---------------------------------------------------------------------------
// Schema
// ---------------------------------------------------------------------------

const documentSchema = z.object({
  title: z.string().min(1, "Title is required"),
  residence_id: z.number({ error: "Residence is required" }),
  description: z.string().optional(),
  document_type: z
    .enum(["general", "warranty", "receipt", "contract", "insurance", "manual"])
    .optional(),
  vendor: z.string().optional(),
  serial_number: z.string().optional(),
  model_number: z.string().optional(),
  purchase_date: z.string().optional(),
  expiry_date: z.string().optional(),
  purchase_price: z.number().optional(),
});

type DocumentFormData = z.infer<typeof documentSchema>;

// ---------------------------------------------------------------------------
// Props
// ---------------------------------------------------------------------------

interface DocumentFormProps {
  document?: DocumentResponse;
  onSubmit: (data: DocumentFormData, file?: File) => void;
  loading?: boolean;
}

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

const documentTypes: { value: DocumentType; label: string }[] = [
  { value: "general", label: "General" },
  { value: "warranty", label: "Warranty" },
  { value: "receipt", label: "Receipt" },
  { value: "contract", label: "Contract" },
  { value: "insurance", label: "Insurance" },
  { value: "manual", label: "Manual" },
];

// ---------------------------------------------------------------------------
// Component
// ---------------------------------------------------------------------------

export function DocumentForm({
  document,
  onSubmit,
  loading = false,
}: DocumentFormProps) {
  const { data: residences } = useResidences();
  const [files, setFiles] = useState<File[]>([]);

  const residenceItems = (Array.isArray(residences) ? residences : []).map((r) => ({
    id: r.residence.id,
    name: r.residence.name,
  }));

  const {
    register,
    handleSubmit,
    setValue,
    watch,
    formState: { errors },
  } = useForm<DocumentFormData>({
    resolver: zodResolver(documentSchema),
    defaultValues: {
      title: document?.title ?? "",
      residence_id: document?.residence_id ?? undefined,
      description: document?.description ?? "",
      document_type: document?.document_type ?? undefined,
      vendor: document?.vendor ?? "",
      serial_number: document?.serial_number ?? "",
      model_number: document?.model_number ?? "",
      purchase_date: document?.purchase_date ?? "",
      expiry_date: document?.expiry_date ?? "",
      purchase_price: document?.purchase_price ?? undefined,
    },
  });

  const residenceId = watch("residence_id");
  const documentType = watch("document_type");
  const purchasePrice = watch("purchase_price");
  const isWarranty = documentType === "warranty";

  const handleFormSubmit = (data: DocumentFormData) => {
    onSubmit(data, files[0]);
  };

  return (
    <form onSubmit={handleSubmit(handleFormSubmit)} className="space-y-8">
      {/* Title & Residence */}
      <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
        <FormField
          label="Title"
          htmlFor="title"
          error={errors.title?.message}
          required
        >
          <Input
            id="title"
            placeholder="Document title"
            aria-invalid={!!errors.title}
            {...register("title")}
          />
        </FormField>

        <FormField
          label="Residence"
          htmlFor="residence_id"
          error={errors.residence_id?.message}
          required
        >
          <LookupSelect
            items={residenceItems}
            value={residenceId}
            onValueChange={(v) => setValue("residence_id", v as number)}
            placeholder="Select residence..."
          />
        </FormField>
      </div>

      {/* Document Type */}
      <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
        <FormField label="Document Type" htmlFor="document_type">
          <Select
            value={documentType ?? ""}
            onValueChange={(v) =>
              setValue("document_type", (v || undefined) as DocumentType | undefined)
            }
          >
            <SelectTrigger className="w-full">
              <SelectValue placeholder="Select type..." />
            </SelectTrigger>
            <SelectContent>
              {documentTypes.map((dt) => (
                <SelectItem key={dt.value} value={dt.value}>
                  {dt.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </FormField>
      </div>

      {/* Description */}
      <FormField label="Description" htmlFor="description">
        <Textarea
          id="description"
          placeholder="Notes about this document..."
          rows={3}
          {...register("description")}
        />
      </FormField>

      {/* Warranty Fields (conditional) */}
      {isWarranty && (
        <div className="space-y-4">
          <h3 className="text-sm font-medium text-muted-foreground">
            Warranty Details
          </h3>
          <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
            <FormField label="Vendor" htmlFor="vendor">
              <Input
                id="vendor"
                placeholder="e.g. Samsung"
                {...register("vendor")}
              />
            </FormField>

            <FormField label="Serial Number" htmlFor="serial_number">
              <Input
                id="serial_number"
                placeholder="SN-12345"
                {...register("serial_number")}
              />
            </FormField>

            <FormField label="Model Number" htmlFor="model_number">
              <Input
                id="model_number"
                placeholder="ABC-100"
                {...register("model_number")}
              />
            </FormField>

            <FormField label="Purchase Price" htmlFor="purchase_price">
              <CurrencyInput
                id="purchase_price"
                value={purchasePrice}
                onChange={(v) => setValue("purchase_price", v)}
                placeholder="0.00"
              />
            </FormField>

            <FormField label="Purchase Date" htmlFor="purchase_date">
              <Input
                id="purchase_date"
                type="date"
                {...register("purchase_date")}
              />
            </FormField>

            <FormField label="Expiry Date" htmlFor="expiry_date">
              <Input
                id="expiry_date"
                type="date"
                {...register("expiry_date")}
              />
            </FormField>
          </div>
        </div>
      )}

      {/* File Upload (create mode only) */}
      {!document && (
        <div className="space-y-2">
          <h3 className="text-sm font-medium text-muted-foreground">
            Attachment
          </h3>
          <FileUpload
            accept="*"
            multiple={false}
            files={files}
            onChange={setFiles}
            label="Upload a document file"
          />
        </div>
      )}

      {/* Submit */}
      <div className="flex justify-end">
        <Button type="submit" disabled={loading}>
          {loading && <Loader2 className="size-4 mr-2 animate-spin" />}
          {document ? "Save Changes" : "Create Document"}
        </Button>
      </div>
    </form>
  );
}
