import { useState, useLayoutEffect } from "react";
import { useLocation } from "react-router-dom";
import { Building2, Plus, Loader2, Globe, ExternalLink } 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 { CompanyDetailSheet } from "@/components/CompanyDetailSheet";

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

  const [sheetOpen, setSheetOpen] = useState(shouldOpenCreate);
  const [selectedCompanyId, setSelectedCompanyId] = useState<number | null>(null);

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

  const { data: companies, isLoading, refetch } = trpc.companies.getAll.useQuery();

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

  const handleRowClick = (companyId: number) => {
    setSelectedCompanyId(companyId);
    setSheetOpen(true);
  };

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

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

  return (
    <div className="container mx-auto p-6 max-w-6xl space-y-6">
      <div className="flex items-center justify-between">
        <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">
            <Building2 className="h-6 w-6 text-primary" />
          </div>
          <div>
            <h1 className="text-2xl font-bold">Companies</h1>
            <p className="text-sm text-muted-foreground">Manage your company records</p>
          </div>
        </div>
        <Button onClick={handleCreateClick}>
          <Plus className="h-4 w-4 mr-2" />
          New Company
        </Button>
      </div>

      <Card>
        <CardHeader className="pb-4">
          <CardTitle className="text-lg">All Companies</CardTitle>
          <CardDescription>
            {companies?.length ?? 0} {companies?.length === 1 ? "company" : "companies"}
          </CardDescription>
        </CardHeader>
        <CardContent>
          {isLoading ? (
            <div className="flex items-center justify-center py-12">
              <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
            </div>
          ) : companies && companies.length > 0 ? (
            <div className="rounded-lg border">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Name</TableHead>
                    <TableHead>Website</TableHead>
                    <TableHead>Created</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {companies.map((company) => (
                    <TableRow
                      key={company.id}
                      className="cursor-pointer hover:bg-muted/50 transition-colors"
                      onClick={() => company.id && handleRowClick(company.id)}
                    >
                      <TableCell className="font-medium">{company.name || "-"}</TableCell>
                      <TableCell>
                        {company.website ? (
                          <span
                            className="inline-flex items-center gap-1.5 text-primary"
                            onClick={(e) => {
                              e.stopPropagation();
                              window.open(company.website!, "_blank");
                            }}
                          >
                            <Globe className="h-3.5 w-3.5" />
                            <span className="truncate max-w-[200px] hover:underline">{company.website}</span>
                            <ExternalLink className="h-3 w-3" />
                          </span>
                        ) : (
                          <span className="text-muted-foreground">-</span>
                        )}
                      </TableCell>
                      <TableCell className="text-muted-foreground">
                        {formatDate(company.createdAt)}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          ) : (
            <div className="text-center py-12 text-muted-foreground">
              <Building2 className="h-12 w-12 mx-auto mb-4 opacity-20" />
              <p>No companies yet.</p>
              <Button variant="link" onClick={handleCreateClick} className="mt-2">
                Create your first company
              </Button>
            </div>
          )}
        </CardContent>
      </Card>

      <CompanyDetailSheet
        open={sheetOpen}
        onOpenChange={setSheetOpen}
        companyId={selectedCompanyId}
        onSuccess={handleSuccess}
      />
    </div>
  );
}
