"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { Home } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Separator } from "@/components/ui/separator";
import { PageHeader } from "@/components/shared/page-header";
import { ErrorBanner } from "@/components/shared/error-banner";
import { HoneyDueFileImport } from "@/components/sharing/honeydue-file-handler";
import { useJoinResidence } from "@/lib/hooks/use-sharing";
import { useDataProvider } from "@/lib/demo/data-provider-context";

export default function JoinResidencePage() {
  const router = useRouter();
  const { basePath } = useDataProvider();
  const joinResidence = useJoinResidence();

  const [code, setCode] = useState("");
  const [fileError, setFileError] = useState<string | null>(null);

  function handleSubmitCode(e: React.FormEvent) {
    e.preventDefault();
    const trimmed = code.trim();
    if (!trimmed) return;

    joinResidence.mutate(trimmed, {
      onSuccess: () => {
        toast.success("Joined residence");
        router.push(`${basePath}/residences`);
      },
      onError: () => {
        toast.error("Failed to join residence");
      },
    });
  }

  function handleFileImport(data: unknown) {
    setFileError(null);

    // Validate that the imported data has a code field
    if (
      typeof data === "object" &&
      data !== null &&
      "code" in data &&
      typeof (data as Record<string, unknown>).code === "string"
    ) {
      const importedCode = (data as Record<string, unknown>).code as string;
      joinResidence.mutate(importedCode, {
        onSuccess: () => {
          toast.success("Joined residence");
          router.push(`${basePath}/residences`);
        },
        onError: () => {
          toast.error("Failed to join residence");
        },
      });
    } else {
      setFileError(
        "Invalid .honeydue file. Expected a share package with a code field.",
      );
    }
  }

  return (
    <div className="space-y-6 max-w-lg mx-auto">
      <PageHeader title="Join a Residence" />

      {joinResidence.isError && (
        <ErrorBanner
          message={
            joinResidence.error instanceof Error
              ? joinResidence.error.message
              : "Failed to join residence. Please check the code and try again."
          }
        />
      )}

      {/* Code entry */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Home className="size-5" />
            Enter Share Code
          </CardTitle>
          <CardDescription>
            Enter the 6-character code you received from the residence owner.
          </CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmitCode} className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="share-code">Share Code</Label>
              <Input
                id="share-code"
                placeholder="ABC123"
                value={code}
                onChange={(e) => setCode(e.target.value.toUpperCase())}
                maxLength={6}
                className="text-center text-lg font-mono tracking-widest"
                autoComplete="off"
              />
            </div>
            <Button
              type="submit"
              className="w-full"
              disabled={code.trim().length === 0 || joinResidence.isPending}
            >
              {joinResidence.isPending ? "Joining..." : "Join Residence"}
            </Button>
          </form>
        </CardContent>
      </Card>

      {/* Divider */}
      <div className="flex items-center gap-4">
        <Separator className="flex-1" />
        <span className="text-xs text-muted-foreground uppercase">or</span>
        <Separator className="flex-1" />
      </div>

      {/* File import */}
      <Card>
        <CardHeader>
          <CardTitle>Import .honeydue File</CardTitle>
          <CardDescription>
            If you received a .honeydue share package file, import it here.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-3">
          <HoneyDueFileImport onImport={handleFileImport} />
          {fileError && (
            <p className="text-sm text-destructive">{fileError}</p>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
