"use client";

import React, { useEffect } from "react";
import { useRouter } from "next/navigation";
import { useDispatch, useSelector } from "react-redux";
import { RootState, AppDispatch } from "@/store/store";
import {
  fetchClients,
  fetchMasterDecks,
  fetchClientPresentations,
  setSelectedClient,
} from "@/store/slices/clientSlice";
import { setSelectedClient as setWizardClient } from "@/store/slices/wizardSlice";
import Wrapper from "@/components/Wrapper";
import Header from "@/app/(presentation-generator)/dashboard/components/Header";
import { PresentationGrid } from "@/app/(presentation-generator)/dashboard/components/PresentationGrid";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Button } from "@/components/ui/button";
import {
  Building2,
  Layers,
  FileText,
  ChevronLeft,
} from "lucide-react";
import { PlusIcon } from "@radix-ui/react-icons";
import { cn } from "@/lib/utils";
import { DashboardApi } from "@/app/(presentation-generator)/services/api/dashboard";

const DashboardPage: React.FC = () => {
  const router = useRouter();
  const dispatch = useDispatch<AppDispatch>();
  const {
    clients,
    selectedClientId,
    masterDecks,
    presentations,
    isLoadingClients,
    isLoadingDecks,
    isLoadingPresentations,
  } = useSelector((s: RootState) => s.client);

  // Fallback: load all presentations for users without clients
  const [allPresentations, setAllPresentations] = React.useState<any[]>([]);
  const [isLoadingAll, setIsLoadingAll] = React.useState(false);

  useEffect(() => {
    dispatch(fetchClients());
  }, [dispatch]);

  // When a client is selected, fetch its data
  useEffect(() => {
    if (selectedClientId) {
      dispatch(fetchMasterDecks(selectedClientId));
      dispatch(fetchClientPresentations(selectedClientId));
    }
  }, [selectedClientId, dispatch]);

  // Fallback: if no clients exist, load all presentations
  useEffect(() => {
    if (!isLoadingClients && clients.length === 0) {
      setIsLoadingAll(true);
      DashboardApi.getPresentations()
        .then((data) => {
          data.sort(
            (a: any, b: any) =>
              new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime()
          );
          setAllPresentations(data);
        })
        .catch(() => setAllPresentations([]))
        .finally(() => setIsLoadingAll(false));
    }
  }, [isLoadingClients, clients.length]);

  const handleSelectClient = (clientId: string) => {
    dispatch(setSelectedClient(clientId));
  };

  const handleNewPresentation = (clientId?: string) => {
    if (clientId) {
      dispatch(setWizardClient(clientId));
    }
    router.push("/generate/upload");
  };

  const handleBack = () => {
    dispatch(setSelectedClient(null));
  };

  const removePresentation = (presentationId: string) => {
    setAllPresentations((prev) =>
      prev.filter((p) => p.id !== presentationId)
    );
  };

  const selectedClient = clients.find((c) => c.id === selectedClientId);

  // If no clients exist, show the original flat dashboard
  if (!isLoadingClients && clients.length === 0) {
    return (
      <div className="min-h-screen bg-[hsl(var(--surface))]">
        <Header />
        <Wrapper>
          <main className="container mx-auto px-4 py-8">
            <section>
              <h2 className="h2 mb-6">
                Recent Presentations
              </h2>
              <PresentationGrid
                presentations={allPresentations}
                type="slide"
                isLoading={isLoadingAll}
                onPresentationDeleted={removePresentation}
              />
            </section>
          </main>
        </Wrapper>
      </div>
    );
  }

  // Client detail view
  if (selectedClient) {
    return (
      <div className="min-h-screen bg-[hsl(var(--surface))]">
        <Header />
        <Wrapper>
          <main className="container mx-auto px-4 py-8 animate-fadeIn">
            {/* Breadcrumb */}
            <div className="flex items-center gap-3 mb-6">
              <Button variant="ghost" size="sm" onClick={handleBack} className="gap-1">
                <ChevronLeft className="w-4 h-4" />
                All Clients
              </Button>
              <span className="text-muted-foreground">/</span>
              <h2 className="h3">{selectedClient.name}</h2>
            </div>

            {/* New Presentation Button */}
            <div className="mb-6">
              <Button
                onClick={() => handleNewPresentation(selectedClient.id)}
                className="rounded-full px-6 shadow-lg"
                size="lg"
              >
                <PlusIcon className="w-5 h-5 mr-2" />
                New Presentation
              </Button>
            </div>

            <Tabs defaultValue="templates">
              <TabsList className="mb-6">
                <TabsTrigger value="templates" className="gap-1.5">
                  <Layers className="w-4 h-4" />
                  Templates
                </TabsTrigger>
                <TabsTrigger value="presentations" className="gap-1.5">
                  <FileText className="w-4 h-4" />
                  Presentations
                </TabsTrigger>
              </TabsList>

              {/* Templates Tab */}
              <TabsContent value="templates">
                {isLoadingDecks ? (
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                    {[...Array(4)].map((_, i) => (
                      <div key={i} className="bg-white rounded-xl p-4 animate-pulse">
                        <div className="aspect-video bg-gray-200 rounded-lg mb-3" />
                        <div className="h-4 bg-gray-200 rounded w-3/4 mb-2" />
                        <div className="h-3 bg-gray-200 rounded w-1/2" />
                      </div>
                    ))}
                  </div>
                ) : masterDecks.length === 0 ? (
                  <div className="text-center py-12 bg-white rounded-xl border-2 border-dashed border-gray-200">
                    <Layers className="w-10 h-10 text-gray-300 mx-auto mb-3" />
                    <p className="text-gray-500 mb-1">No master decks yet</p>
                    <p className="text-sm text-gray-400">Upload master decks in the Admin panel</p>
                  </div>
                ) : (
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                    {masterDecks.map((deck) => (
                      <div
                        key={deck.id}
                        className="bg-white rounded-xl border hover:border-[#5146E5]/40 hover:shadow-md transition-all cursor-pointer overflow-hidden"
                        onClick={() => {
                          dispatch(setWizardClient(selectedClient.id));
                          router.push("/generate/upload");
                        }}
                      >
                        <div className="aspect-video bg-gray-100 flex items-center justify-center">
                          {deck.thumbnail_url ? (
                            <img
                              src={deck.thumbnail_url}
                              alt={deck.name}
                              className="w-full h-full object-cover"
                            />
                          ) : (
                            <Layers className="w-10 h-10 text-gray-300" />
                          )}
                        </div>
                        <div className="p-4">
                          <h3 className="font-medium text-sm truncate">{deck.name}</h3>
                          <p className="text-xs text-gray-400 mt-1">
                            {deck.layout_count} layouts
                          </p>
                          <span
                            className={cn(
                              "inline-block mt-2 text-[10px] font-semibold uppercase px-2 py-0.5 rounded",
                              deck.parse_status === "completed"
                                ? "bg-green-50 text-green-600"
                                : deck.parse_status === "failed"
                                ? "bg-red-50 text-red-600"
                                : "bg-yellow-50 text-yellow-600"
                            )}
                          >
                            {deck.parse_status}
                          </span>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </TabsContent>

              {/* Presentations Tab */}
              <TabsContent value="presentations">
                {isLoadingPresentations ? (
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                    {[...Array(4)].map((_, i) => (
                      <div key={i} className="bg-white rounded-xl p-4 animate-pulse">
                        <div className="aspect-video bg-gray-200 rounded-lg mb-3" />
                        <div className="h-4 bg-gray-200 rounded w-3/4" />
                      </div>
                    ))}
                  </div>
                ) : presentations.length === 0 ? (
                  <div className="text-center py-12 bg-white rounded-xl border-2 border-dashed border-gray-200">
                    <FileText className="w-10 h-10 text-gray-300 mx-auto mb-3" />
                    <p className="text-gray-500 mb-3">No presentations yet</p>
                    <Button
                      onClick={() => handleNewPresentation(selectedClient.id)}
                      className="bg-[#5146E5] hover:bg-[#5146E5]/90 text-white rounded-full"
                    >
                      Create First Presentation
                    </Button>
                  </div>
                ) : (
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                    {presentations.map((p) => (
                      <div
                        key={p.id}
                        className="bg-white rounded-xl border hover:border-[#5146E5]/40 hover:shadow-md transition-all cursor-pointer overflow-hidden"
                        onClick={() => router.push(`/presentation?id=${p.id}`)}
                      >
                        <div className="aspect-video bg-gray-100 flex items-center justify-center">
                          <FileText className="w-10 h-10 text-gray-300" />
                        </div>
                        <div className="p-4">
                          <h3 className="font-medium text-sm truncate">
                            {p.title || "Untitled"}
                          </h3>
                          <div className="flex items-center gap-2 mt-2">
                            <span
                              className={cn(
                                "text-[10px] font-semibold uppercase px-2 py-0.5 rounded",
                                p.status === "approved"
                                  ? "bg-green-50 text-green-600"
                                  : p.status === "in_review"
                                  ? "bg-blue-50 text-blue-600"
                                  : "bg-yellow-50 text-yellow-600"
                              )}
                            >
                              {p.status || "draft"}
                            </span>
                            <span className="text-xs text-gray-400">
                              {new Date(p.updated_at).toLocaleDateString()}
                            </span>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </TabsContent>
            </Tabs>
          </main>
        </Wrapper>
      </div>
    );
  }

  // Client grid view (top-level)
  return (
    <div className="min-h-screen bg-[#E9E8F8]">
      <Header />
      <Wrapper>
        <main className="container mx-auto px-4 py-8">
          <div className="flex items-center justify-between mb-6">
            <h2 className="text-2xl font-roboto font-medium">Your Clients</h2>
            <Button
              onClick={() => handleNewPresentation()}
              className="bg-[#5146E5] hover:bg-[#5146E5]/90 text-white rounded-full px-6"
            >
              <PlusIcon className="w-4 h-4 mr-2" />
              New Presentation
            </Button>
          </div>

          {isLoadingClients ? (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {[...Array(3)].map((_, i) => (
                <div key={i} className="bg-white rounded-xl p-6 animate-pulse">
                  <div className="flex items-center gap-4 mb-4">
                    <div className="w-12 h-12 bg-gray-200 rounded-lg" />
                    <div className="space-y-2 flex-1">
                      <div className="h-5 bg-gray-200 rounded w-2/3" />
                      <div className="h-3 bg-gray-200 rounded w-1/3" />
                    </div>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {clients.map((client) => (
                <div
                  key={client.id}
                  onClick={() => handleSelectClient(client.id)}
                  className="bg-white rounded-xl border-2 border-transparent hover:border-[hsl(var(--primary))]/40 hover:shadow-lg hover:-translate-y-1 transition-all duration-200 cursor-pointer p-6 group animate-fadeIn"
                >
                  <div className="flex items-center gap-4 mb-4">
                    <div className="w-12 h-12 rounded-lg bg-[hsl(var(--primary-light))] flex items-center justify-center flex-shrink-0 group-hover:bg-[hsl(var(--primary))]/20 transition-colors">
                      {client.logo_url ? (
                        <img
                          src={client.logo_url}
                          alt={client.name}
                          className="w-8 h-8 object-contain"
                        />
                      ) : (
                        <Building2 className="w-6 h-6 text-[hsl(var(--primary))]" />
                      )}
                    </div>
                    <div>
                      <h3 className="font-semibold text-lg">{client.name}</h3>
                    </div>
                  </div>
                  <Button
                    variant="outline"
                    size="sm"
                    className="w-full rounded-full mt-2 group-hover:bg-[hsl(var(--primary))] group-hover:text-white group-hover:border-[hsl(var(--primary))] transition-all"
                    onClick={(e) => {
                      e.stopPropagation();
                      handleNewPresentation(client.id);
                    }}
                  >
                    <PlusIcon className="w-4 h-4 mr-1" />
                    New Presentation
                  </Button>
                </div>
              ))}
            </div>
          )}
        </main>
      </Wrapper>
    </div>
  );
};

export default DashboardPage;
