"use client";

import { use, useState } from "react";
import { useRouter } from "next/navigation";
import dynamic from "next/dynamic";
import Link from "next/link";
import { MapPin, Pencil, Share2, Trash2, FileDown, Plus, ClipboardList, ArrowRight } from "lucide-react";
import { toast } from "sonner";
import { useDataProvider } from "@/lib/demo/data-provider-context";

import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { PageHeader } from "@/components/shared/page-header";
import { LoadingSkeleton } from "@/components/shared/loading-skeleton";
import { ErrorBanner } from "@/components/shared/error-banner";
import { ConfirmDialog } from "@/components/shared/confirm-dialog";
import { ResidenceSummary } from "@/components/residences/residence-summary";
import { useResidence, useDeleteResidence } from "@/lib/hooks/use-residences";
import { useTasksByResidence } from "@/lib/hooks/use-tasks";

const KanbanBoard = dynamic(
  () => import("@/components/tasks/kanban-board").then((mod) => ({ default: mod.KanbanBoard })),
  { loading: () => <LoadingSkeleton variant="kanban" /> }
);

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

export default function ResidenceDetailPage({ params }: ResidenceDetailPageProps) {
  const { id: rawId } = use(params);
  const id = Number(rawId);
  const router = useRouter();
  const { basePath, sharing } = useDataProvider();

  const { data: residence, isLoading, error, refetch } = useResidence(id);
  const deleteResidence = useDeleteResidence();
  const { data: kanbanData, isLoading: tasksLoading } = useTasksByResidence(id);

  const [deleteOpen, setDeleteOpen] = useState(false);
  const [reportLoading, setReportLoading] = useState(false);
  const [reportMessage, setReportMessage] = useState<string | null>(null);

  const handleGenerateReport = async () => {
    setReportLoading(true);
    setReportMessage(null);
    try {
      const result = await sharing.generateTasksReport(id);
      const msg = result.message || "Report sent to your email!";
      setReportMessage(msg);
      toast.success(msg);
    } catch {
      setReportMessage("Failed to generate report.");
      toast.error("Failed to generate report");
    } finally {
      setReportLoading(false);
    }
  };

  // Compute task summary directly from kanban columns (always accurate)
  const taskSummary = kanbanData
    ? {
        total: kanbanData.columns.reduce((sum, col) => sum + col.tasks.length, 0),
        in_progress: kanbanData.columns.find((c) => c.name === "in_progress_tasks")?.tasks.length ?? 0,
        overdue: kanbanData.columns.find((c) => c.name === "overdue_tasks")?.tasks.length ?? 0,
        completed: kanbanData.columns.find((c) => c.name === "completed_tasks")?.tasks.length ?? 0,
      }
    : undefined;

  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>
    );
  }

  const address = [
    residence.street_address,
    residence.apartment_unit,
    residence.city,
    residence.state_province,
    residence.postal_code,
    residence.country,
  ]
    .filter(Boolean)
    .join(", ");

  const details = [
    { label: "Bedrooms", value: residence.bedrooms },
    { label: "Bathrooms", value: residence.bathrooms },
    { label: "Sq. Footage", value: residence.square_footage?.toLocaleString() },
    { label: "Year Built", value: residence.year_built },
    { label: "Property Type", value: residence.property_type?.name },
  ].filter((d) => d.value != null);

  return (
    <div className="space-y-6">
      <PageHeader title={residence.name}>
        {residence.is_owner && (
          <Button
            variant="outline"
            size="sm"
            onClick={() => router.push(`${basePath}/residences/${id}/share`)}
          >
            <Share2 className="size-4 mr-2" />
            Share
          </Button>
        )}
        <Button
          variant="outline"
          size="sm"
          onClick={handleGenerateReport}
          disabled={reportLoading}
        >
          <FileDown className="size-4 mr-2" />
          {reportLoading ? "Generating..." : "Report"}
        </Button>
        <Button
          variant="outline"
          size="sm"
          onClick={() => router.push(`${basePath}/residences/${id}/edit`)}
        >
          <Pencil className="size-4 mr-2" />
          Edit
        </Button>
        <Button
          variant="outline"
          size="sm"
          onClick={() => setDeleteOpen(true)}
        >
          <Trash2 className="size-4 mr-2" />
          Delete
        </Button>
      </PageHeader>

      {/* Report Message */}
      {reportMessage && (
        <div className="rounded-md border px-4 py-3 text-sm">
          {reportMessage}
        </div>
      )}

      {/* Address */}
      {address && (
        <div className="flex items-center gap-2 text-muted-foreground">
          <MapPin className="size-4 shrink-0" />
          <span>{address}</span>
        </div>
      )}

      {/* Task Summary */}
      {taskSummary && (
        <ResidenceSummary
          totalTasks={taskSummary.total}
          inProgress={taskSummary.in_progress}
          overdue={taskSummary.overdue}
          completed={taskSummary.completed}
        />
      )}

      {/* Tasks Kanban Board */}
      <div>
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-2">
            <h2 className="font-heading text-lg font-semibold">Tasks</h2>
            <Link
              href={`${basePath}/tasks?residence_id=${id}`}
              className="text-sm font-medium text-muted-foreground hover:text-foreground transition-colors flex items-center gap-1"
            >
              View all
              <ArrowRight className="size-3.5" />
            </Link>
          </div>
          <Button asChild size="sm" className="rounded-xl shadow-[var(--shadow-warm-sm)]">
            <Link href={`${basePath}/tasks/new?residence_id=${id}`}>
              <Plus className="size-4 mr-1.5" />
              Add Task
            </Link>
          </Button>
        </div>

        {tasksLoading && <LoadingSkeleton variant="kanban" />}

        {!tasksLoading && kanbanData && kanbanData.columns.every((col) => col.tasks.length === 0) && (
          <div className="flex flex-col items-center justify-center py-16 text-center rounded-2xl border border-dashed border-border/60 bg-muted/20">
            <ClipboardList className="size-8 text-muted-foreground/50 mb-3" />
            <p className="text-sm font-medium text-muted-foreground">No tasks yet</p>
            <p className="text-xs text-muted-foreground/70 mt-1 max-w-xs">
              Add your first task to start tracking what needs to get done around this home.
            </p>
            <Button asChild size="sm" className="mt-4 rounded-full">
              <Link href={`${basePath}/tasks/new?residence_id=${id}`}>
                <Plus className="size-4 mr-1.5" />
                Add Task
              </Link>
            </Button>
          </div>
        )}

        {!tasksLoading && kanbanData && !kanbanData.columns.every((col) => col.tasks.length === 0) && (
          <KanbanBoard data={kanbanData} />
        )}
      </div>

      {/* Description */}
      {residence.description && (
        <Card>
          <CardHeader>
            <CardTitle className="text-sm text-muted-foreground">Description</CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-sm whitespace-pre-wrap">{residence.description}</p>
          </CardContent>
        </Card>
      )}

      {/* Property Details */}
      {details.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle className="text-sm text-muted-foreground">Property Details</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-2 gap-4 sm:grid-cols-4">
              {details.map((d) => (
                <div key={d.label}>
                  <p className="text-xs text-muted-foreground">{d.label}</p>
                  <p className="text-sm font-medium">{d.value}</p>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}

      {/* Delete Dialog */}
      <ConfirmDialog
        open={deleteOpen}
        onOpenChange={setDeleteOpen}
        title="Delete Residence"
        description="Are you sure you want to delete this residence? This action cannot be undone."
        confirmLabel="Delete"
        variant="destructive"
        loading={deleteResidence.isPending}
        onConfirm={() => {
          deleteResidence.mutate(id, {
            onSuccess: () => {
              toast.success("Residence deleted");
              router.push(`${basePath}/residences`);
            },
            onError: () => {
              toast.error("Failed to delete residence");
            },
          });
        }}
      />
    </div>
  );
}
