"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import {
  Badge,
  Box,
  Chip,
  Grid,
  Group,
  ScrollArea,
  SimpleGrid,
  Stack,
  Text,
  TextInput,
  Title,
} from "@mantine/core";
import { notifications } from "@mantine/notifications";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { motion } from "framer-motion";
import { Search, Smartphone } from "lucide-react";
import { AppCreationLockedGate } from "@/components/app-creation/AppCreationLockedGate";
import { AppCreationOptionalCard } from "@/components/app-creation/AppCreationOptionalCard";
import { AppCreationPlanCard } from "@/components/app-creation/AppCreationPlanCard";
import { AppCreationQuotePanel } from "@/components/app-creation/AppCreationQuotePanel";
import { DashboardPage } from "@/components/dashboard/DashboardPage";
import { PageHeader } from "@/components/dashboard/PageHeader";
import { platformOptions } from "@/data/onboarding";
import { appCreationService } from "@/services/appCreationService";
import { useAppCreationStore } from "@/store/appCreationStore";
import { useAuthStore } from "@/store/authStore";
import { useClientProposalStore } from "@/store/clientProposalStore";
import { colors } from "@/styles/tokens";
import { formatCurrency } from "@/utils/format";

const PLATFORM_LABELS: Record<string, string> = {
  pwa: "PWA",
  android: "Android",
  ios: "iOS",
  admin: "Painel Admin",
};

export default function CriarMeuAppPage() {
  const token = useAuthStore((s) => s.token);
  const queryClient = useQueryClient();
  const clientProposal = useClientProposalStore((s) => s.current);

  const {
    selectedPlanId,
    selectedOptionalIds,
    platforms,
    search,
    categoryFilter,
    quote,
    setPlanId,
    toggleOptional,
    togglePlatform,
    setSearch,
    setCategoryFilter,
    setQuote,
  } = useAppCreationStore();

  const [calculating, setCalculating] = useState(false);

  const { data: access, isLoading: accessLoading } = useQuery({
    queryKey: ["app-creation", "access"],
    queryFn: () => appCreationService.getAccess(token!),
    enabled: Boolean(token),
  });

  const { data: catalog, isLoading: catalogLoading } = useQuery({
    queryKey: ["app-creation", "catalog"],
    queryFn: () => appCreationService.getCatalog(token!),
    enabled: Boolean(token) && Boolean(access?.unlocked),
  });

  const plans = catalog?.plans ?? [];
  const categories = catalog?.categories ?? [];
  const optionals = catalog?.optionals ?? [];

  const filteredOptionals = useMemo(() => {
    let list = optionals;
    if (categoryFilter) {
      list = list.filter((o) => o.categorySlug === categoryFilter);
    }
    if (search.trim()) {
      const q = search.toLowerCase();
      list = list.filter(
        (o) =>
          o.name.toLowerCase().includes(q) ||
          o.description?.toLowerCase().includes(q) ||
          o.slug.includes(q),
      );
    }
    return list;
  }, [optionals, categoryFilter, search]);

  const recalculate = useCallback(async () => {
    if (!token || !selectedPlanId) {
      setQuote(null);
      return;
    }
    setCalculating(true);
    try {
      const result = await appCreationService.calculate(token, {
        plan_id: selectedPlanId,
        optional_ids: selectedOptionalIds,
        billing_cycle: "monthly",
        platforms,
      });
      setQuote(result);
    } catch {
      setQuote(null);
    } finally {
      setCalculating(false);
    }
  }, [
    token,
    selectedPlanId,
    selectedOptionalIds,
    platforms,
    setQuote,
  ]);

  useEffect(() => {
    if (access?.unlocked && selectedPlanId) {
      void recalculate();
    }
  }, [access?.unlocked, selectedPlanId, selectedOptionalIds, platforms, recalculate]);

  useEffect(() => {
    if (plans.length && !selectedPlanId) {
      const featured = plans.find((p) => p.featured) ?? plans[0];
      setPlanId(featured.id);
    }
  }, [plans, selectedPlanId, setPlanId]);

  const saveMutation = useMutation({
    mutationFn: () =>
      appCreationService.saveQuote(token!, {
        plan_id: selectedPlanId!,
        optional_ids: selectedOptionalIds,
        billing_cycle: "monthly",
        platforms,
      }),
    onSuccess: () => {
      notifications.show({ color: "green", message: "Proposta salva no painel." });
      queryClient.invalidateQueries({ queryKey: ["app-creation"] });
    },
  });

  const contractMutation = useMutation({
    mutationFn: () => appCreationService.contract(token!),
    onSuccess: () => {
      notifications.show({
        color: "green",
        title: "Contratação registrada",
        message: "Desenvolvimento do app confirmado.",
      });
    },
  });

  if (accessLoading) {
    return (
      <DashboardPage title="Criar Meu App">
        <Text c="dimmed">Carregando…</Text>
      </DashboardPage>
    );
  }

  if (!access?.unlocked) {
    return (
      <DashboardPage title="Criar Meu App">
        <PageHeader
          title="Criar Meu App"
          description="Planos de criação do aplicativo — liberados após o planejamento estratégico."
        />
        <AppCreationLockedGate message={access?.message} />
      </DashboardPage>
    );
  }

  return (
    <DashboardPage title="Criar Meu App">
      <PageHeader
        title="Criar Meu App"
        description="Planos de criação do aplicativo · funcionalidades · opcionais · contratação de desenvolvimento."
        actions={
          clientProposal?.status === "contracted" ? (
            <Badge color="green" variant="light">
              Planejamento contratado
            </Badge>
          ) : null
        }
      />

      <Grid gutter="xl">
        <Grid.Col span={{ base: 12, lg: 8 }}>
          <Stack gap={48}>
            <motion.section
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
            >
              <Stack gap="md" mb="lg">
                <Group gap="sm">
                  <Smartphone color={colors.primary} />
                  <Title order={4} c={colors.white}>
                    Planos de criação do app
                  </Title>
                </Group>
                <Text size="sm" c="dimmed">
                  Escolha Starter, Business ou Enterprise. Estes planos não aparecem no
                  site público.
                </Text>
              </Stack>
              {catalogLoading ? (
                <Text c="dimmed">Carregando planos…</Text>
              ) : (
                <SimpleGrid cols={{ base: 1, md: 3 }} spacing="lg">
                  {plans.map((plan) => (
                    <AppCreationPlanCard
                      key={plan.id}
                      plan={plan}
                      selected={selectedPlanId === plan.id}
                      onSelect={() => setPlanId(plan.id)}
                    />
                  ))}
                </SimpleGrid>
              )}
            </motion.section>

            <section>
              <Title order={5} c={colors.white} mb="md">
                Plataformas
              </Title>
              <Group gap="sm">
                {platformOptions.map((p) => (
                  <Chip
                    key={p.id}
                    checked={platforms.includes(p.id)}
                    onChange={() => togglePlatform(p.id)}
                    variant="outline"
                  >
                    {PLATFORM_LABELS[p.id] ?? p.label}
                  </Chip>
                ))}
                {platforms.includes("admin") === false && (
                  <Chip
                    checked={platforms.includes("admin")}
                    onChange={() => togglePlatform("admin")}
                    variant="outline"
                  >
                    Painel Admin
                  </Chip>
                )}
              </Group>
            </section>

            <section>
              <Group justify="space-between" mb="md" wrap="wrap">
                <Title order={5} c={colors.white}>
                  Opcionais ({optionals.length})
                </Title>
                <TextInput
                  placeholder="Buscar opcionais…"
                  leftSection={<Search size={16} />}
                  value={search}
                  onChange={(e) => setSearch(e.target.value)}
                  maw={320}
                  style={{ flex: 1 }}
                />
              </Group>
              <ScrollArea mb="md" type="auto" offsetScrollbars>
                <Group gap="xs" wrap="nowrap">
                  <Chip
                    checked={!categoryFilter}
                    onChange={() => setCategoryFilter(null)}
                  >
                    Todos
                  </Chip>
                  {categories.map((cat) => (
                    <Chip
                      key={cat.id}
                      checked={categoryFilter === cat.slug}
                      onChange={() => setCategoryFilter(cat.slug)}
                      style={
                        cat.color
                          ? { borderColor: cat.color }
                          : undefined
                      }
                    >
                      {cat.name}
                    </Chip>
                  ))}
                </Group>
              </ScrollArea>
              <Box
                style={{
                  maxHeight: 520,
                  overflowY: "auto",
                  paddingRight: 8,
                }}
              >
                <SimpleGrid cols={{ base: 1, sm: 2, md: 3 }} spacing="sm">
                  {filteredOptionals.map((opt) => (
                    <AppCreationOptionalCard
                      key={opt.id}
                      optional={opt}
                      selected={selectedOptionalIds.includes(opt.id)}
                      onToggle={() => toggleOptional(opt.id)}
                      showPrice
                      priceLabel={`${formatCurrency(opt.price)} · único`}
                    />
                  ))}
                </SimpleGrid>
              </Box>
            </section>
          </Stack>
        </Grid.Col>

        <Grid.Col span={{ base: 12, lg: 4 }}>
          <AppCreationQuotePanel
            quote={quote}
            loading={calculating}
            onSaveQuote={() => saveMutation.mutate()}
            onContract={() => contractMutation.mutate()}
            contracting={contractMutation.isPending}
          />
        </Grid.Col>
      </Grid>
    </DashboardPage>
  );
}
