"use client";

import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { FormField } from "@/components/shared/form-field";
import { LookupSelect } from "@/components/shared/lookup-select";
import { StarRating } from "@/components/shared/star-rating";
import { useContractorSpecialties } from "@/lib/hooks/use-lookups";
import { useResidences } from "@/lib/hooks/use-residences";
import type { ContractorResponse } from "@/lib/api/contractors";

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

const contractorSchema = z.object({
  name: z.string().min(1, "Name is required"),
  company: z.string().optional(),
  phone: z.string().optional(),
  email: z.string().email("Invalid email address").or(z.literal("")).optional(),
  website: z.string().optional(),
  notes: z.string().optional(),
  residence_id: z.number().optional(),
  specialty_ids: z.array(z.number()).optional(),
  is_favorite: z.boolean().optional(),
  rating: z.number().optional(),
});

export type ContractorFormValues = z.infer<typeof contractorSchema>;

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

interface ContractorFormProps {
  contractor?: ContractorResponse;
  onSubmit: (data: ContractorFormValues) => void;
  loading?: boolean;
}

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

export function ContractorForm({ contractor, onSubmit, loading }: ContractorFormProps) {
  const { data: specialties } = useContractorSpecialties();
  const { data: residencesData } = useResidences();

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

  const {
    register,
    handleSubmit,
    setValue,
    watch,
    formState: { errors },
  } = useForm<ContractorFormValues>({
    resolver: zodResolver(contractorSchema),
    defaultValues: {
      name: contractor?.name ?? "",
      company: contractor?.company ?? "",
      phone: contractor?.phone ?? "",
      email: contractor?.email ?? "",
      website: contractor?.website ?? "",
      notes: contractor?.notes ?? "",
      residence_id: contractor?.residence_id ?? undefined,
      specialty_ids: contractor?.specialties.map((s) => s.id) ?? [],
      is_favorite: contractor?.is_favorite ?? false,
      rating: contractor?.rating ?? 0,
    },
  });

  const selectedSpecialtyIds = watch("specialty_ids") ?? [];
  const rating = watch("rating") ?? 0;

  function toggleSpecialty(id: number) {
    const current = selectedSpecialtyIds;
    const next = current.includes(id)
      ? current.filter((sid) => sid !== id)
      : [...current, id];
    setValue("specialty_ids", next, { shouldDirty: true });
  }

  return (
    <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
      {/* Name (required) */}
      <FormField label="Name" htmlFor="name" required error={errors.name?.message}>
        <Input id="name" placeholder="e.g. John's Plumbing" {...register("name")} />
      </FormField>

      {/* Company */}
      <FormField label="Company" htmlFor="company" error={errors.company?.message}>
        <Input id="company" placeholder="Company name" {...register("company")} />
      </FormField>

      {/* Contact fields grid */}
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
        <FormField label="Phone" htmlFor="phone" error={errors.phone?.message}>
          <Input id="phone" type="tel" placeholder="(555) 123-4567" {...register("phone")} />
        </FormField>
        <FormField label="Email" htmlFor="email" error={errors.email?.message}>
          <Input id="email" type="email" placeholder="contractor@example.com" {...register("email")} />
        </FormField>
        <FormField label="Website" htmlFor="website" error={errors.website?.message} className="sm:col-span-2">
          <Input id="website" placeholder="https://example.com" {...register("website")} />
        </FormField>
      </div>

      {/* Residence */}
      <FormField label="Residence" htmlFor="residence_id">
        <LookupSelect
          items={residenceItems}
          value={watch("residence_id")}
          onValueChange={(v) => setValue("residence_id", v, { shouldDirty: true })}
          placeholder="Select a residence (optional)"
        />
      </FormField>

      {/* Specialties */}
      <FormField label="Specialties" htmlFor="specialties">
        <div className="flex flex-wrap gap-2">
          {specialties.map((s) => {
            const selected = selectedSpecialtyIds.includes(s.id);
            return (
              <Badge
                key={s.id}
                variant={selected ? "default" : "outline"}
                className="cursor-pointer select-none"
                onClick={() => toggleSpecialty(s.id)}
              >
                {s.icon && <span className="mr-1">{s.icon}</span>}
                {s.name}
              </Badge>
            );
          })}
        </div>
      </FormField>

      {/* Rating */}
      <FormField label="Rating" htmlFor="rating">
        <StarRating
          value={rating}
          onChange={(v) => setValue("rating", v, { shouldDirty: true })}
        />
      </FormField>

      {/* Notes */}
      <FormField label="Notes" htmlFor="notes" error={errors.notes?.message}>
        <Textarea id="notes" placeholder="Any additional notes..." rows={3} {...register("notes")} />
      </FormField>

      {/* Submit */}
      <div className="flex justify-end gap-2">
        <Button type="submit" disabled={loading}>
          {loading ? "Saving..." : contractor ? "Update Contractor" : "Create Contractor"}
        </Button>
      </div>
    </form>
  );
}
