"use client";

import { useState, useMemo } from "react";
import { useRouter } from "next/navigation";
import { Upload, Wrench } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle,
} from "@/components/ui/dialog";
import { PageHeader } from "@/components/shared/page-header";
import { LoadingSkeleton } from "@/components/shared/loading-skeleton";
import { ErrorBanner } from "@/components/shared/error-banner";
import { EmptyState } from "@/components/shared/empty-state";
import { HoneyDueFileImport } from "@/components/sharing/honeydue-file-handler";
import { ContractorCard } from "@/components/contractors/contractor-card";
import { ContractorFilters } from "@/components/contractors/contractor-filters";
import { useContractors, useToggleFavorite, useCreateContractor } from "@/lib/hooks/use-contractors";
import { useDataProvider } from "@/lib/demo/data-provider-context";

export default function ContractorsPage() {
  const router = useRouter();
  const { basePath } = useDataProvider();
  const { data: contractors, isLoading, isError, error, refetch } = useContractors();
  const toggleFavorite = useToggleFavorite();
  const createContractor = useCreateContractor();

  const [search, setSearch] = useState("");
  const [specialtyId, setSpecialtyId] = useState<number | undefined>(undefined);
  const [favoritesOnly, setFavoritesOnly] = useState(false);
  const [importOpen, setImportOpen] = useState(false);
  const [importError, setImportError] = useState<string | null>(null);

  const filtered = useMemo(() => {
    if (!Array.isArray(contractors)) return [];
    let list = contractors;

    // Search filter (name or company)
    if (search.trim()) {
      const q = search.toLowerCase();
      list = list.filter(
        (c) =>
          c.name.toLowerCase().includes(q) ||
          c.company.toLowerCase().includes(q),
      );
    }

    // Specialty filter
    if (specialtyId != null) {
      list = list.filter((c) =>
        c.specialties.some((s) => s.id === specialtyId),
      );
    }

    // Favorites filter
    if (favoritesOnly) {
      list = list.filter((c) => c.is_favorite);
    }

    return list;
  }, [contractors, search, specialtyId, favoritesOnly]);

  function handleContractorImport(data: unknown) {
    setImportError(null);

    if (
      typeof data === "object" &&
      data !== null &&
      "type" in data &&
      (data as Record<string, unknown>).type === "honeydue_contractor_share" &&
      "contractor" in data
    ) {
      const contractor = (data as Record<string, unknown>).contractor as Record<string, unknown>;
      createContractor.mutate(
        {
          name: (contractor.name as string) ?? "",
          company: contractor.company as string | undefined,
          phone: contractor.phone as string | undefined,
          email: contractor.email as string | undefined,
          website: contractor.website as string | undefined,
          notes: contractor.notes as string | undefined,
          street_address: contractor.street_address as string | undefined,
          city: contractor.city as string | undefined,
          state_province: contractor.state_province as string | undefined,
          postal_code: contractor.postal_code as string | undefined,
          specialty_ids: contractor.specialty_ids as number[] | undefined,
          rating: contractor.rating as number | undefined,
        },
        {
          onSuccess: () => {
            setImportOpen(false);
          },
          onError: (err) => {
            setImportError(
              err instanceof Error ? err.message : "Failed to import contractor.",
            );
          },
        },
      );
    } else {
      setImportError("Invalid .honeydue file. Expected a contractor share file.");
    }
  }

  return (
    <div className="space-y-6">
      <PageHeader
        title="Your Pros"
        description="The people you trust to get the job done"
        actionLabel="Add a Pro"
        onAction={() => router.push(`${basePath}/contractors/new`)}
      >
        <Button
          variant="outline"
          size="sm"
          onClick={() => {
            setImportError(null);
            setImportOpen(true);
          }}
        >
          <Upload className="size-4 mr-2" />
          Import .honeydue
        </Button>
      </PageHeader>

      {isError && (
        <ErrorBanner
          message={error instanceof Error ? error.message : "Failed to load contractors."}
          onRetry={() => refetch()}
        />
      )}

      {isLoading && <LoadingSkeleton variant="list" count={5} />}

      {!isLoading && !isError && Array.isArray(contractors) && (
        <>
          <ContractorFilters
            search={search}
            onSearchChange={setSearch}
            specialtyId={specialtyId}
            onSpecialtyChange={setSpecialtyId}
            favoritesOnly={favoritesOnly}
            onFavoritesOnlyChange={setFavoritesOnly}
          />

          {filtered.length === 0 ? (
            <EmptyState
              icon={Wrench}
              title="No pros saved yet"
              description={
                (contractors?.length ?? 0) === 0
                  ? "Save your go-to plumber, electrician, or handyman so you always know who to call."
                  : "Try adjusting your search or filters."
              }
              actionLabel={contractors.length === 0 ? "Add Contractor" : undefined}
              onAction={contractors.length === 0 ? () => router.push(`${basePath}/contractors/new`) : undefined}
            />
          ) : (
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-2 gap-5">
              {filtered.map((c) => (
                <ContractorCard
                  key={c.id}
                  contractor={c}
                  onToggleFavorite={(id) => toggleFavorite.mutate(id)}
                />
              ))}
            </div>
          )}
        </>
      )}

      {/* Import .honeydue dialog */}
      <Dialog open={importOpen} onOpenChange={setImportOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Import Contractor</DialogTitle>
            <DialogDescription>
              Import a contractor from a .honeydue file shared with you.
            </DialogDescription>
          </DialogHeader>
          <HoneyDueFileImport onImport={handleContractorImport} />
          {importError && (
            <p className="text-sm text-destructive">{importError}</p>
          )}
          {createContractor.isPending && (
            <p className="text-sm text-muted-foreground">Importing...</p>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}
