"use client";

import { useState } from "react";
import { Button } from "@/app/shadcn_components/ui/button";
import { Input } from "@/app/shadcn_components/ui/input";
import { Card } from "@/app/shadcn_components/ui/card";
import { Pencil } from "lucide-react";
import {
  Select,
  SelectTrigger,
  SelectContent,
  SelectItem,
  SelectValue,
} from "@/app/shadcn_components/ui/select";
import usePostcodeLookup from "./usePostcodeLookup";

interface AddressItem {
  uprn: string;
  address: string;
}

export default function AddressSearch({
  onAddressSelect,
  onPostcodeSelect,
  postcode,
}: {
  onAddressSelect: (address: AddressItem | null) => void; // ✅ Fix type
  onPostcodeSelect: (postcode: string) => void;
  postcode: string;
}) {
  const [addresses, setAddresses] = useState<AddressItem[]>([]);
  const [selectedAddress, setSelectedAddress] = useState<AddressItem | null>(
    null
  );
  const [showDropdown, setShowDropdown] = useState(false);
  const [triggerSearch, setTriggerSearch] = useState(false);
  const [loadingAddresses, setLoadingAddresses] = useState(false);
  const [addressError, setAddressError] = useState<string | null>(null);

  const { data, isFetching, refetch } = usePostcodeLookup(
    postcode,
    triggerSearch
  );

  async function handleSearch() {
    if (!postcode.trim()) return;
    setTriggerSearch(true);
    const validation = await refetch();
    setTriggerSearch(false);

    if (!validation.data || validation.data.status !== 200) return;

    const validatedPostcode =
      validation.data.result?.postcode?.toUpperCase() ?? postcode.toUpperCase();

    // Use the validated postcode for fetching addresses
    onPostcodeSelect(validatedPostcode);

    setLoadingAddresses(true);
    setAddressError(null);

    try {
      const res = await fetch(
        `/api/postcode/${encodeURIComponent(validatedPostcode)}/addresses`
      );
      const json = await res.json();

      if (!res.ok) {
        setAddressError(json.error || "Unable to retrieve addresses");
        setShowDropdown(false);
      } else if (json.results?.length) {
        const mapped = json.results.map((r: any) => ({
          address: r.address,
          uprn: r.uprn,
          propertyType: r.propertyType,
          builtForm: r.builtForm,
        }));
        setAddresses(mapped);
        setShowDropdown(true);
      } else {
        setAddressError("No addresses found for this postcode");
      }
    } catch {
      setAddressError("There was an issue contacting the address service.");
    } finally {
      setLoadingAddresses(false);
    }
  }

  function handleSelectAddress(value: string) {
    const selected = addresses.find((a) => a.address === value) || null;
    setSelectedAddress(selected);
    setShowDropdown(false);
    onAddressSelect(selected);
  }

  function handleChangeAddress() {
    setSelectedAddress(null);
    setShowDropdown(true);
    onAddressSelect(null);
  }

  const showInvalid = data && data.status === 404;
  const showServerError = data && data.status === 500;
  const isLoading = isFetching || loadingAddresses;

  return (
    <Card className="p-6">
      {!selectedAddress && (
        <div className="flex gap-2 mb-4">
          <Input
            placeholder="Enter postcode"
            value={postcode}
            onChange={(e) => onPostcodeSelect(e.target.value.toUpperCase())}
          />
          <Button
            onClick={handleSearch}
            disabled={isLoading || !postcode}
            className="bg-brandbrown text-white"
          >
            {isLoading ? "Searching..." : "Search"}
          </Button>
        </div>
      )}

      {/* Validation and errors */}
      {showInvalid && (
        <p className="text-sm text-red-600 mb-3">
          Invalid postcode — please check and try again.
        </p>
      )}
      {showServerError && (
        <p className="text-sm text-orange-600 mb-3">
          The postcode service is currently unavailable. Please try again later.
        </p>
      )}
      {addressError && (
        <p className="text-sm text-orange-600 mb-3">{addressError}</p>
      )}

      {/* Address dropdown */}
      {showDropdown && addresses.length > 0 && (
        <div className="mt-2">
          <label className="block text-sm text-gray-700 mb-2">
            Select your address
          </label>
          <Select
            onValueChange={handleSelectAddress}
            value={selectedAddress?.address || undefined} // ✅ fix value binding
          >
            <SelectTrigger className="w-full border-gray-300">
              <SelectValue placeholder="Choose an address" />
            </SelectTrigger>
            <SelectContent>
              {addresses.map((a) => (
                <SelectItem key={a.uprn} value={a.address}>
                  {a.address}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
      )}

      {/* Selected address display */}
      {selectedAddress && !showDropdown && (
        <div className="bg-gray-100 border rounded-xl p-6 mt-4 flex flex-col justify-between min-h-[140px]">
          <div>
            <h3 className="text-lg font-semibold text-brandblue mb-2">
              Selected Address
            </h3>
            <p className="text-gray-700 text-sm break-words">
              {selectedAddress.address}
            </p>
          </div>
          <div className="flex justify-end mt-4">
            <Button
              size="sm"
              variant="outline"
              onClick={handleChangeAddress}
              className="flex gap-1 text-brandbrown border-brandbrown"
            >
              <Pencil className="w-4 h-4" />
              Change
            </Button>
          </div>
        </div>
      )}
    </Card>
  );
}
