"use client";

import { use, useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { toast } from "sonner";
import { Phone, Mail, Globe, Star, Pencil, Trash2, FileDown } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
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 { StarRating } from "@/components/shared/star-rating";
import { downloadHoneyDueFile } from "@/components/sharing/honeydue-file-handler";
import {
  useContractor,
  useContractorTasks,
  useDeleteContractor,
  useToggleFavorite,
} from "@/lib/hooks/use-contractors";
import { useDataProvider } from "@/lib/demo/data-provider-context";

export default function ContractorDetailPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id: idParam } = use(params);
  const id = Number(idParam);
  const router = useRouter();
  const { basePath } = useDataProvider();

  const { data: contractor, isLoading, isError, error, refetch } = useContractor(id);
  const { data: tasks } = useContractorTasks(id);
  const deleteContractor = useDeleteContractor();
  const toggleFavorite = useToggleFavorite();

  const [deleteOpen, setDeleteOpen] = useState(false);

  function handleDelete() {
    deleteContractor.mutate(id, {
      onSuccess: () => {
        toast.success("Contractor deleted");
        router.push(`${basePath}/contractors`);
      },
      onError: () => {
        toast.error("Failed to delete contractor");
      },
    });
  }

  if (isLoading) {
    return <LoadingSkeleton variant="detail" />;
  }

  if (isError) {
    return (
      <ErrorBanner
        message={error instanceof Error ? error.message : "Failed to load contractor."}
        onRetry={() => refetch()}
      />
    );
  }

  if (!contractor) return null;

  return (
    <div className="space-y-6 max-w-3xl">
      <PageHeader title={contractor.name} description={contractor.company || undefined}>
        <Button
          variant="ghost"
          size="icon"
          onClick={() => toggleFavorite.mutate(contractor.id)}
        >
          <Star
            className={
              contractor.is_favorite
                ? "size-5 fill-yellow-400 text-yellow-400"
                : "size-5 text-muted-foreground"
            }
          />
        </Button>
        <Button
          variant="outline"
          size="sm"
          onClick={() => {
            const exportData = {
              type: "honeydue_contractor_share",
              version: 1,
              contractor: {
                name: contractor.name,
                company: contractor.company,
                phone: contractor.phone,
                email: contractor.email,
                website: contractor.website,
                notes: contractor.notes,
                street_address: contractor.street_address,
                city: contractor.city,
                state_province: contractor.state_province,
                postal_code: contractor.postal_code,
                specialty_ids: contractor.specialties.map((s) => s.id),
                rating: contractor.rating,
              },
              exported_at: new Date().toISOString(),
            };
            const safeName = contractor.name.replace(/[^a-zA-Z0-9_-]/g, "_").toLowerCase();
            downloadHoneyDueFile(exportData, `${safeName}-contractor`);
          }}
        >
          <FileDown className="size-4 mr-2" />
          Share
        </Button>
        <Button variant="outline" size="sm" asChild>
          <Link href={`/app/contractors/${contractor.id}/edit`}>
            <Pencil className="size-4 mr-2" />
            Edit
          </Link>
        </Button>
        <Button
          variant="destructive"
          size="sm"
          onClick={() => setDeleteOpen(true)}
        >
          <Trash2 className="size-4 mr-2" />
          Delete
        </Button>
      </PageHeader>

      {/* Contact info */}
      <Card>
        <CardHeader>
          <CardTitle>Contact Information</CardTitle>
        </CardHeader>
        <CardContent className="space-y-3">
          {contractor.phone && (
            <div className="flex items-center gap-3">
              <Phone className="size-4 text-muted-foreground" />
              <a href={`tel:${contractor.phone}`} className="text-sm hover:underline">
                {contractor.phone}
              </a>
            </div>
          )}
          {contractor.email && (
            <div className="flex items-center gap-3">
              <Mail className="size-4 text-muted-foreground" />
              <a href={`mailto:${contractor.email}`} className="text-sm hover:underline">
                {contractor.email}
              </a>
            </div>
          )}
          {contractor.website && (
            <div className="flex items-center gap-3">
              <Globe className="size-4 text-muted-foreground" />
              <a
                href={contractor.website.startsWith("http") ? contractor.website : `https://${contractor.website}`}
                target="_blank"
                rel="noopener noreferrer"
                className="text-sm hover:underline"
              >
                {contractor.website}
              </a>
            </div>
          )}
          {!contractor.phone && !contractor.email && !contractor.website && (
            <p className="text-sm text-muted-foreground">No contact information provided.</p>
          )}
        </CardContent>
      </Card>

      {/* Specialties */}
      {contractor.specialties.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle>Specialties</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex flex-wrap gap-2">
              {contractor.specialties.map((s) => (
                <Badge key={s.id} variant="secondary">
                  {s.icon && <span className="mr-1">{s.icon}</span>}
                  {s.name}
                </Badge>
              ))}
            </div>
          </CardContent>
        </Card>
      )}

      {/* Rating */}
      {contractor.rating != null && contractor.rating > 0 && (
        <Card>
          <CardHeader>
            <CardTitle>Rating</CardTitle>
          </CardHeader>
          <CardContent>
            <StarRating value={contractor.rating} readonly />
          </CardContent>
        </Card>
      )}

      {/* Notes */}
      {contractor.notes && (
        <Card>
          <CardHeader>
            <CardTitle>Notes</CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-sm whitespace-pre-wrap">{contractor.notes}</p>
          </CardContent>
        </Card>
      )}

      {/* Linked tasks */}
      <Card>
        <CardHeader>
          <CardTitle>Linked Tasks</CardTitle>
        </CardHeader>
        <CardContent>
          {!tasks || tasks.length === 0 ? (
            <p className="text-sm text-muted-foreground">No tasks linked to this contractor.</p>
          ) : (
            <div className="space-y-2">
              {tasks.map((task) => (
                <div key={task.id}>
                  <div className="flex items-center justify-between py-2">
                    <div>
                      <p className="text-sm font-medium">{task.title}</p>
                      <p className="text-xs text-muted-foreground">
                        {task.residence_name}
                        {task.due_date && ` - Due ${task.due_date}`}
                      </p>
                    </div>
                    <Badge variant="outline">{task.status}</Badge>
                  </div>
                  <Separator />
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      {/* Delete confirmation */}
      <ConfirmDialog
        open={deleteOpen}
        onOpenChange={setDeleteOpen}
        title="Delete Contractor"
        description={`Are you sure you want to delete "${contractor.name}"? This action cannot be undone.`}
        confirmLabel="Delete"
        variant="destructive"
        loading={deleteContractor.isPending}
        onConfirm={handleDelete}
      />
    </div>
  );
}
