import React from 'react';
import { Card } from '@tamagui/card';
import { YStack, XStack } from '@tamagui/stacks';
import { SizableText as Text } from '@tamagui/text';
import { Pressable } from '@tamagui/react-native-web-lite';
import { Tabs, Separator } from 'tamagui';
import { useAdminTheme } from '../theme';
import { withAlpha } from './colors';

export function MobileCard({
  children,
  className,
  style,
  ...rest
}: React.ComponentProps<typeof YStack>) {
  const { surface, border, shadow, glassSurface, glassBorder, glassShadow } = useAdminTheme();
  return (
    <YStack
      className={['admin-fade-up', className].filter(Boolean).join(' ')}
      backgroundColor={glassSurface ?? surface}
      borderRadius={20}
      borderWidth={2}
      borderColor={glassBorder ?? border}
      shadowColor={glassShadow ?? shadow}
      shadowOpacity={0.16}
      shadowRadius={16}
      shadowOffset={{ width: 0, height: 10 }}
      padding="$3.5"
      space="$2"
      style={{
        ...style,
      }}
      {...rest}
    >
      {children}
    </YStack>
  );
}

export function PillBadge({
  tone = 'muted',
  children,
}: {
  tone?: 'success' | 'warning' | 'danger' | 'muted';
  children: React.ReactNode;
}) {
  const { successText, warningText, dangerText, muted, surfaceMuted, border } = useAdminTheme();
  const palette: Record<typeof tone, { bg: string; text: string; border: string }> = {
    success: {
      bg: withAlpha(successText, 0.16),
      text: successText,
      border: withAlpha(successText, 0.35),
    },
    warning: {
      bg: withAlpha(warningText, 0.16),
      text: warningText,
      border: withAlpha(warningText, 0.35),
    },
    danger: {
      bg: withAlpha(dangerText, 0.16),
      text: dangerText,
      border: withAlpha(dangerText, 0.35),
    },
    muted: {
      bg: surfaceMuted,
      text: muted,
      border,
    },
  };
  const colors = palette[tone] ?? palette.muted;
  return (
    <XStack
      alignItems="center"
      paddingHorizontal="$3"
      paddingVertical="$1.5"
      borderRadius={999}
      borderWidth={1}
      backgroundColor={colors.bg}
      borderColor={colors.border}
    >
      <Text fontSize="$xs" fontWeight="700" color={colors.text}>
        {children}
      </Text>
    </XStack>
  );
}

export function CTAButton({
  label,
  onPress,
  tone = 'primary',
  fullWidth = true,
  disabled = false,
  loading = false,
  style,
  iconLeft,
  iconRight,
}: {
  label: string;
  onPress: () => void;
  tone?: 'primary' | 'ghost' | 'danger';
  fullWidth?: boolean;
  disabled?: boolean;
  loading?: boolean;
  style?: any;
  iconLeft?: React.ReactNode;
  iconRight?: React.ReactNode;
}) {
  const { primary, surface, border, text, danger, glassSurfaceStrong } = useAdminTheme();
  const isPrimary = tone === 'primary';
  const isDanger = tone === 'danger';
  const isDisabled = disabled || loading;
  const backgroundColor = isDanger ? danger : isPrimary ? primary : glassSurfaceStrong ?? surface;
  const borderColor = isPrimary || isDanger ? 'transparent' : border;
  const labelColor = isPrimary || isDanger ? 'white' : text;
  const primaryStyle = isPrimary
    ? {
        boxShadow: `0 18px 28px ${withAlpha(primary, 0.4)}`,
      }
    : undefined;
  return (
    <Pressable
      onPress={isDisabled ? undefined : onPress}
      disabled={isDisabled}
      style={{
        width: fullWidth ? '100%' : undefined,
        flex: fullWidth ? undefined : 1,
        opacity: isDisabled ? 0.6 : 1,
        ...style,
      }}
    >
      <XStack
        height={52}
        borderRadius={18}
        alignItems="center"
        justifyContent="center"
        backgroundColor={backgroundColor}
        borderWidth={isPrimary || isDanger ? 0 : 2}
        borderColor={borderColor}
        space="$2"
        style={primaryStyle}
      >
        {iconLeft}
        <Text fontSize="$sm" fontWeight="800" color={labelColor}>
          {label}
        </Text>
        {iconRight}
      </XStack>
    </Pressable>
  );
}

export function KpiTile({
  icon: IconCmp,
  label,
  value,
  note,
  color,
}: {
  icon: React.ComponentType<{ size?: number; color?: string }>;
  label: string;
  value: string | number;
  note?: string;
  color?: string;
}) {
  const { textStrong, textMuted, primary, accentSoft } = useAdminTheme();
  const iconBg = color ? withAlpha(color, 0.12) : accentSoft;
  const iconColor = color || primary;

  return (
    <MobileCard borderRadius={14} padding="$2.5" width="31%" minWidth={100} space="$1.5">
      <XStack
        width={28}
        height={28}
        borderRadius={8}
        backgroundColor={iconBg}
        alignItems="center"
        justifyContent="center"
      >
        <IconCmp size={14} color={iconColor} />
      </XStack>

      <YStack space="$0">
        <Text fontSize="$xl" fontWeight="900" color={textStrong} letterSpacing={-0.5} lineHeight="$xl">
          {value}
        </Text>
        <Text fontSize={9} fontWeight="700" color={textMuted} textTransform="uppercase" letterSpacing={0.4}>
          {label}
        </Text>
      </YStack>

      {note ? (
        <Text fontSize={9} fontWeight="800" color={iconColor} opacity={0.9} textTransform="uppercase">
          {note}
        </Text>
      ) : null}
    </MobileCard>
  );
}

export function KpiStrip({
  items
}: {
  items: Array<{
    icon: React.ComponentType<{ size?: number; color?: string }>;
    label: string;
    value: string | number;
    color?: string;
    note?: string;
    tone?: 'accent' | 'neutral';
  }>
}) {
  const { glassSurface, glassSurfaceStrong, glassBorder, border, textStrong, textMuted, primary, surfaceMuted, surface } = useAdminTheme();
  const cardSurface = surfaceMuted ?? glassSurfaceStrong ?? glassSurface ?? surface;
  const cardBorder = glassBorder ?? border;
  const separatorColor = withAlpha(textStrong, 0.12);
  const innerSeparatorColor = withAlpha(textStrong, 0.08);

  return (
    <XStack flexWrap="wrap" gap="$2">
      {items.map((item, index) => {
        const isNeutral = item.tone === 'neutral';
        const iconColor = isNeutral ? textStrong : item.color || primary;
        const iconBg = isNeutral ? surfaceMuted : withAlpha(iconColor, 0.12);

        return (
          <Card
            key={index}
            backgroundColor={cardSurface}
            borderRadius={14}
            borderWidth={1}
            borderColor={cardBorder}
            padding="$2.5"
            flexGrow={1}
            flexBasis="48%"
            minWidth={150}
            maxWidth={220}
          >
            <XStack alignItems="center" space="$1">
              <Text
                fontSize={32}
                fontWeight="900"
                color={textStrong}
                letterSpacing={-1}
                lineHeight={34}
              >
                {item.value}
              </Text>
              <Separator vertical backgroundColor={separatorColor} height={32} />
              <YStack alignItems="center" space="$0.5">
                <XStack
                  width={28}
                  height={28}
                  borderRadius={10}
                  backgroundColor={iconBg}
                  alignItems="center"
                  justifyContent="center"
                >
                  <item.icon size={16} color={iconColor} />
                </XStack>
                <Text
                  fontSize={9}
                  fontWeight="700"
                  color={textMuted}
                  textTransform="uppercase"
                  letterSpacing={0.5}
                  textAlign="center"
                >
                  {item.label}
                </Text>
                <Separator backgroundColor={innerSeparatorColor} width={28} alignSelf="center" />
                {item.note ? (
                  <Text fontSize={9} fontWeight="800" color={iconColor} opacity={0.9} textTransform="uppercase">
                    {item.note}
                  </Text>
                ) : null}
              </YStack>
            </XStack>
          </Card>
        );
      })}
    </XStack>
  );
}

export function SkeletonCard({ height = 80 }: { height?: number }) {
  return (
    <MobileCard className="mobile-skeleton" height={height} />
  );
}

export function ActionTile({
  icon: IconCmp,
  label,
  note,
  noteTone = 'muted',
  color,
  onPress,
  disabled = false,
  variant = 'grid',
  delayMs = 0,
}: {
  icon: React.ComponentType<{ size?: number; color?: string }>;
  label: string;
  note?: string;
  noteTone?: 'warning' | 'muted';
  color: string;
  onPress?: () => void;
  disabled?: boolean;
  variant?: 'grid' | 'cluster';
  delayMs?: number;
}) {
  const { textStrong, glassSurface, muted, warningText } = useAdminTheme();
  const noteColor = noteTone === 'warning' ? warningText : muted;
  const isCluster = variant === 'cluster';
  const backgroundColor = withAlpha(color, 0.12);
  const borderColor = withAlpha(color, 0.4);
  const shadowColor = withAlpha(color, 0.35);
  const iconShadow = withAlpha(color, 0.5);
  const tileStyle = {
    ...(delayMs ? { animationDelay: `${delayMs}ms` } : {}),
    backgroundImage: `linear-gradient(135deg, ${backgroundColor}, ${withAlpha(color, 0.08)})`,
    boxShadow: isCluster ? `0 12px 18px ${shadowColor}` : `0 20px 30px ${shadowColor}`,
  };
  return (
    <Pressable
      onPress={disabled ? undefined : onPress}
      style={{
        width: isCluster ? '100%' : '48%',
        flex: isCluster ? 1 : undefined,
        marginBottom: isCluster ? 0 : 12,
        opacity: disabled ? 0.5 : 1,
      }}
      disabled={disabled}
    >
      <YStack
        className="admin-fade-up"
        style={tileStyle}
        borderRadius={isCluster ? 14 : 16}
        padding="$3"
        space="$2.5"
        backgroundColor={glassSurface ?? backgroundColor}
        borderWidth={2}
        borderColor={borderColor}
        minHeight={120}
        alignItems="center"
        justifyContent="center"
      >
        <XStack
          width={44}
          height={44}
          borderRadius={14}
          backgroundColor={color}
          alignItems="center"
          justifyContent="center"
          style={{ boxShadow: `0 6px 14px ${iconShadow}` }}
        >
          <IconCmp size={18} color="white" />
        </XStack>
        <Text fontSize="$sm" fontWeight="800" color={textStrong} textAlign="center">
          {label}
        </Text>
        {note ? (
          <Text fontSize="$xs" fontWeight="700" color={noteColor} textAlign="center">
            {note}
          </Text>
        ) : null}
      </YStack>
    </Pressable>
  );
}

export function FloatingActionButton({
  onPress,
  label,
  icon: IconCmp,
}: {
  onPress: () => void;
  label: string;
  icon: React.ComponentType<{ size?: number; color?: string }>;
}) {
  const { primary, shadow } = useAdminTheme();
  const [pressed, setPressed] = React.useState(false);
  return (
    <Pressable
      onPress={onPress}
      onPressIn={() => setPressed(true)}
      onPressOut={() => setPressed(false)}
      onPointerLeave={() => setPressed(false)}
      style={{
        position: 'fixed',
        right: 18,
        bottom: 'calc(env(safe-area-inset-bottom, 0px) + 96px)',
        zIndex: 60,
        transform: pressed ? 'scale(0.96)' : 'scale(1)',
        opacity: pressed ? 0.92 : 1,
        transition: 'transform 140ms ease, opacity 140ms ease',
      }}
      aria-label={label}
    >
      <XStack
        height={56}
        paddingHorizontal="$4"
        borderRadius={999}
        alignItems="center"
        justifyContent="center"
        space="$2"
        backgroundColor={primary}
        shadowColor={shadow}
        shadowOpacity={0.2}
        shadowRadius={16}
        shadowOffset={{ width: 0, height: 8 }}
      >
        <IconCmp size={18} color="white" />
        <Text fontSize="$sm" fontWeight="800" color="white">
          {label}
        </Text>
      </XStack>
    </Pressable>
  );
}

export function ContentTabs({
  value,
  onValueChange,
  tabs,
  header,
}: {
  value: string;
  onValueChange: (val: string) => void;
  tabs: { value: string; label: string; content: React.ReactNode }[];
  header?: React.ReactNode;
}) {
  const { border, muted, primary } = useAdminTheme();

  return (
    <Tabs
      defaultValue={value}
      value={value}
      onValueChange={onValueChange}
      orientation="horizontal"
      flexDirection="column"
      borderRadius="$4"
      borderWidth={1}
      borderColor={border}
      overflow="hidden"
    >
      <Tabs.List separator={<Separator vertical />} disablePassBorderRadius="bottom" backgroundColor="$surface">
        {tabs.map((tab) => (
          <Tabs.Tab
            key={tab.value}
            value={tab.value}
            flex={1}
            unstyled
            paddingVertical="$3"
            alignItems="center"
            justifyContent="center"
            backgroundColor={value === tab.value ? primary : 'transparent'}
            hoverStyle={{ backgroundColor: value === tab.value ? primary : '$backgroundHover' }}
          >
            <Text
              fontSize="$sm"
              fontWeight={value === tab.value ? '700' : '500'}
              color={value === tab.value ? '#fff' : muted}
            >
              {tab.label}
            </Text>
          </Tabs.Tab>
        ))}
      </Tabs.List>

      {header}

      {tabs.map((tab) => (
        <Tabs.Content key={tab.value} value={tab.value}>
          {tab.content}
        </Tabs.Content>
      ))}
    </Tabs>
  );
}
