"use client";

import { use } from "react";
import { useRouter } from "next/navigation";
import { ArrowLeft } from "lucide-react";
import { Button } from "@/components/ui/button";
import { PageHeader } from "@/components/shared/page-header";
import { LoadingSkeleton } from "@/components/shared/loading-skeleton";
import { ErrorBanner } from "@/components/shared/error-banner";
import { ShareCodeDisplay } from "@/components/sharing/share-code-display";
import { UserManagement } from "@/components/sharing/user-management";
import { HoneyDueFileExport } from "@/components/sharing/honeydue-file-handler";
import { useResidence } from "@/lib/hooks/use-residences";
import { useDataProvider } from "@/lib/demo/data-provider-context";

interface SharePageProps {
  params: Promise<{ id: string }>;
}

export default function ResidenceSharePage({ params }: SharePageProps) {
  const { id: rawId } = use(params);
  const id = Number(rawId);
  const router = useRouter();
  const { basePath } = useDataProvider();

  const { data: residence, isLoading, error, refetch } = useResidence(id);

  if (isLoading) {
    return (
      <div className="space-y-6">
        <LoadingSkeleton variant="detail" />
      </div>
    );
  }

  if (error || !residence) {
    return (
      <div className="space-y-6">
        <ErrorBanner
          message="Failed to load residence."
          onRetry={() => refetch()}
        />
      </div>
    );
  }

  // Build the exportable residence data
  const exportData = {
    type: "honeydue_residence_share",
    version: 1,
    residence: {
      name: residence.name,
      property_type_id: residence.property_type_id,
      street_address: residence.street_address,
      apartment_unit: residence.apartment_unit,
      city: residence.city,
      state_province: residence.state_province,
      postal_code: residence.postal_code,
      country: residence.country,
      bedrooms: residence.bedrooms,
      bathrooms: residence.bathrooms,
      square_footage: residence.square_footage,
      lot_size: residence.lot_size,
      year_built: residence.year_built,
      description: residence.description,
    },
    exported_at: new Date().toISOString(),
  };

  const safeFilename = residence.name.replace(/[^a-zA-Z0-9_-]/g, "_").toLowerCase();

  return (
    <div className="space-y-6 max-w-2xl">
      <PageHeader title={`Share "${residence.name}"`}>
        <Button
          variant="ghost"
          size="sm"
          onClick={() => router.push(`${basePath}/residences/${id}`)}
        >
          <ArrowLeft className="size-4 mr-2" />
          Back
        </Button>
      </PageHeader>

      {/* Share code section — only owner can manage */}
      {residence.is_owner && (
        <ShareCodeDisplay residenceId={id} />
      )}

      {/* Export .honeydue file */}
      {residence.is_owner && (
        <div className="flex items-center gap-3">
          <HoneyDueFileExport
            data={exportData}
            filename={`${safeFilename}-residence`}
            label="Export Residence (.honeydue)"
          />
          <p className="text-sm text-muted-foreground">
            Download residence data as a portable .honeydue file.
          </p>
        </div>
      )}

      {/* User / member management */}
      <UserManagement residenceId={id} />
    </div>
  );
}
