import { useState, useLayoutEffect } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import { Handshake, Plus, Loader2, Users, ExternalLink, LayoutGrid, Table as TableIcon } from "lucide-react";
import { trpc } from "@/lib/trpc";
import { Button } from "@/components/ui/button";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { DealDetailSheet } from "@/components/DealDetailSheet";
import { ContactDetailSheet } from "@/components/ContactDetailSheet";
import { PhaseBadge } from "@/lib/phase-config";
import { KanbanBoard } from "@/components/KanbanBoard";
import { cn } from "@/lib/utils";

interface Contact {
  id?: number;
  firstName?: string;
  lastName?: string;
  mail?: string;
}

interface Deal {
  id?: number;
  name?: string;
  phase?: string;
  mainContact?: Contact[];
  createdAt?: string;
  updatedAt?: string;
}

type ViewMode = "table" | "kanban";

export default function DealsPage() {
  const navigate = useNavigate();
  const location = useLocation();
  const shouldOpenCreate = Boolean(location.state?.openCreate);

  const [viewMode, setViewMode] = useState<ViewMode>("kanban");
  const [sheetOpen, setSheetOpen] = useState(shouldOpenCreate);
  const [selectedDealId, setSelectedDealId] = useState<number | null>(null);
  
  // Contact sheet state
  const [contactSheetOpen, setContactSheetOpen] = useState(false);
  const [selectedContactId, setSelectedContactId] = useState<number | null>(null);

  // Clear navigation state after handling
  useLayoutEffect(() => {
    if (shouldOpenCreate) {
      window.history.replaceState({}, document.title);
    }
  }, [shouldOpenCreate]);

  const { data: dealsData, isLoading, refetch } = trpc.deals.getAll.useQuery();
  
  const updateMutation = trpc.deals.update.useMutation({
    onSuccess: () => {
      refetch();
    },
  });
  
  // Cast to Deal[] to work around complex type inference
  const deals = dealsData as Deal[] | undefined;

  const formatDate = (dateStr?: string) => {
    if (!dateStr) return "-";
    return new Date(dateStr).toLocaleDateString();
  };

  const handleRowClick = (dealId: number) => {
    setSelectedDealId(dealId);
    setSheetOpen(true);
  };

  const handleCreateClick = () => {
    setSelectedDealId(null);
    setSheetOpen(true);
  };

  const handleContactClick = (e: React.MouseEvent, contactId: number) => {
    e.stopPropagation();
    setSelectedContactId(contactId);
    setContactSheetOpen(true);
  };

  const handleSuccess = () => {
    refetch();
  };

  const handlePhaseChange = (dealId: number, newPhase: string) => {
    updateMutation.mutate({
      id: dealId,
      phase: newPhase as "New" | "Demo scheduled" | "Contract signed" | "Lost",
    });
  };

  // Helper to format contact name
  const formatContactName = (contact: Contact): string => {
    const parts = [contact.firstName, contact.lastName].filter(Boolean);
    return parts.join(" ") || "Unknown";
  };

  return (
    <div className="p-6 h-full flex flex-col gap-6 min-w-0">
      <div className="flex items-center justify-between flex-shrink-0 flex-wrap gap-4 min-w-0">
        <div className="flex items-center gap-3">
          <div className="p-2.5 rounded-xl bg-gradient-to-br from-primary/20 to-primary/5 border border-primary/20">
            <Handshake className="h-6 w-6 text-primary" />
          </div>
          <div>
            <h1 className="text-2xl font-bold">Deals</h1>
            <p className="text-sm text-muted-foreground">Manage your deal pipeline</p>
          </div>
        </div>
        <div className="flex items-center gap-2">
          {/* View Toggle */}
          <div className="flex items-center rounded-lg border bg-muted/30 p-1">
            <button
              onClick={() => setViewMode("kanban")}
              className={cn(
                "flex items-center gap-1.5 px-3 py-1.5 rounded-md text-sm font-medium transition-colors",
                viewMode === "kanban"
                  ? "bg-background shadow-sm text-foreground"
                  : "text-muted-foreground hover:text-foreground"
              )}
            >
              <LayoutGrid className="h-4 w-4" />
              Kanban
            </button>
            <button
              onClick={() => setViewMode("table")}
              className={cn(
                "flex items-center gap-1.5 px-3 py-1.5 rounded-md text-sm font-medium transition-colors",
                viewMode === "table"
                  ? "bg-background shadow-sm text-foreground"
                  : "text-muted-foreground hover:text-foreground"
              )}
            >
              <TableIcon className="h-4 w-4" />
              Table
            </button>
          </div>
          <Button onClick={handleCreateClick}>
            <Plus className="h-4 w-4 mr-2" />
            New Deal
          </Button>
        </div>
      </div>

      {isLoading ? (
        <div className="flex items-center justify-center py-12 flex-1">
          <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
        </div>
      ) : viewMode === "kanban" ? (
        // Kanban View
        deals && deals.length > 0 ? (
          <div className="flex-1 min-h-0 min-w-0 overflow-x-auto overflow-y-hidden">
            <KanbanBoard
              deals={deals}
              onDealClick={handleRowClick}
              onContactClick={handleContactClick}
              onPhaseChange={handlePhaseChange}
            />
          </div>
        ) : (
          <div className="text-center py-12 text-muted-foreground flex-1">
            <Handshake className="h-12 w-12 mx-auto mb-4 opacity-20" />
            <p>No deals yet.</p>
            <Button variant="link" onClick={handleCreateClick} className="mt-2">
              Create your first deal
            </Button>
          </div>
        )
      ) : (
        // Table View
        <Card>
          <CardHeader className="pb-4">
            <CardTitle className="text-lg">All Deals</CardTitle>
            <CardDescription>
              {deals?.length ?? 0} {deals?.length === 1 ? "deal" : "deals"}
            </CardDescription>
          </CardHeader>
          <CardContent>
            {deals && deals.length > 0 ? (
              <div className="rounded-lg border">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Name</TableHead>
                      <TableHead>Phase</TableHead>
                      <TableHead>Contact</TableHead>
                      <TableHead>Created</TableHead>
                      <TableHead className="w-[80px]"></TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {deals.map((deal) => {
                      const contact = deal.mainContact?.[0];
                      
                      return (
                        <TableRow
                          key={deal.id}
                          className="cursor-pointer hover:bg-muted/50 transition-colors"
                          onClick={() => deal.id && handleRowClick(deal.id)}
                        >
                          <TableCell className="font-medium">{deal.name || "-"}</TableCell>
                          <TableCell>
                            {deal.phase ? (
                              <PhaseBadge phase={deal.phase} />
                            ) : (
                              <span className="text-muted-foreground">-</span>
                            )}
                          </TableCell>
                          <TableCell>
                            {contact?.id ? (
                              <button
                                onClick={(e) => handleContactClick(e, contact.id!)}
                                className="inline-flex items-center gap-1.5 px-2 py-1 rounded-md bg-blue-500/10 text-blue-600 hover:bg-blue-500/20 transition-colors text-sm"
                              >
                                <Users className="h-3.5 w-3.5" />
                                <span>{formatContactName(contact)}</span>
                              </button>
                            ) : (
                              <span className="text-muted-foreground">-</span>
                            )}
                          </TableCell>
                          <TableCell className="text-muted-foreground">
                            {formatDate(deal.createdAt)}
                          </TableCell>
                          <TableCell>
                            <Button
                              variant="ghost"
                              size="sm"
                              className="h-8 w-8 p-0"
                              onClick={(e) => {
                                e.stopPropagation();
                                if (deal.id) navigate(`/deals/${deal.id}`);
                              }}
                            >
                              <ExternalLink className="h-4 w-4" />
                            </Button>
                          </TableCell>
                        </TableRow>
                      );
                    })}
                  </TableBody>
                </Table>
              </div>
            ) : (
              <div className="text-center py-12 text-muted-foreground">
                <Handshake className="h-12 w-12 mx-auto mb-4 opacity-20" />
                <p>No deals yet.</p>
                <Button variant="link" onClick={handleCreateClick} className="mt-2">
                  Create your first deal
                </Button>
              </div>
            )}
          </CardContent>
        </Card>
      )}

      <DealDetailSheet
        open={sheetOpen}
        onOpenChange={setSheetOpen}
        dealId={selectedDealId}
        onSuccess={handleSuccess}
      />

      <ContactDetailSheet
        open={contactSheetOpen}
        onOpenChange={setContactSheetOpen}
        contactId={selectedContactId}
        onSuccess={handleSuccess}
      />
    </div>
  );
}
