import { Ionicons } from "@expo/vector-icons";
import { useState } from "react";
import { ActivityIndicator, Pressable, Text, View } from "react-native";
import { useClaims, type Debt } from "@/src/hooks/useDebts";
import { useTranslation } from "react-i18next";
import { formatEur } from "@/src/utils/format";

function ClaimCard({ debt }: { debt: Debt }) {
  const [expanded, setExpanded] = useState(false);
  const isClosed = debt.closedAt !== null;
  const accentColor = isClosed ? "#10b981" : "#7c3aed";
  const pct = Math.round(debt.progressPercent);
  const { t } = useTranslation();

  // creditorUserName here = the debtor's name (person who owes me money)
  const debtorName = debt.creditorUserName ?? t('debts.unknown');

  return (
    <View
      className="bg-white rounded-2xl mx-4 mb-2 overflow-hidden"
      style={{ borderWidth: 1, borderColor: isClosed ? "#d1fae5" : "#e0e7ff" }}
    >
      <Pressable
        onPress={() => setExpanded((v) => !v)}
        className="flex-row items-center px-4 py-3 active:opacity-80"
      >
        <View
          className="w-9 h-9 rounded-full items-center justify-center mr-3"
          style={{ backgroundColor: isClosed ? "#d1fae5" : "#e0e7ff" }}
        >
          <Ionicons
            name={isClosed ? "checkmark-circle" : "cash-outline"}
            size={18}
            color={accentColor}
          />
        </View>

        <View className="flex-1 mr-2">
          <View className="flex-row items-center justify-between mb-1.5">
            <Text className="text-sm font-semibold text-gray-900" numberOfLines={1}>
              {debt.label}
            </Text>
            <Text className="text-xs font-bold ml-2" style={{ color: accentColor }}>
              {pct}%
            </Text>
          </View>
          <View className="h-1.5 bg-gray-100 rounded-full overflow-hidden">
            <View
              className="h-full rounded-full"
              style={{ width: `${debt.progressPercent}%`, backgroundColor: accentColor }}
            />
          </View>
          <Text className="text-xs text-gray-400 mt-1">
            {t('debts.fromDebtor', { name: debtorName, amount: formatEur(debt.remainingAmount, false) })}
          </Text>
        </View>

        <Ionicons
          name={expanded ? "chevron-up" : "chevron-down"}
          size={14}
          color="#9ca3af"
        />
      </Pressable>

      {expanded && (
        <View style={{ borderTopWidth: 1, borderTopColor: "#f3f4f6" }}>
          <View className="flex-row px-4 py-3 justify-between">
            <View>
              <Text className="text-xs text-gray-400">{t('debts.received')}</Text>
              <Text className="text-sm font-semibold" style={{ color: accentColor }}>
                {formatEur(debt.paidAmount, false)}
              </Text>
            </View>
            <View className="items-center">
              <Text className="text-xs text-gray-400">{t('debts.total')}</Text>
              <Text className="text-sm font-semibold text-gray-700">
                {formatEur(debt.totalAmount, false)}
              </Text>
            </View>
            <View className="items-end">
              <Text className="text-xs text-gray-400">{t('debts.pendingLabel')}</Text>
              <Text className="text-sm font-semibold text-gray-900">
                {formatEur(debt.remainingAmount, false)}
              </Text>
            </View>
          </View>
          {debt.notes && (
            <Text className="text-xs text-gray-400 px-4 pb-3">{debt.notes}</Text>
          )}
          {isClosed && (
            <View className="mx-4 mb-3 px-3 py-2 rounded-xl" style={{ backgroundColor: "#d1fae5" }}>
              <Text className="text-xs font-medium text-center" style={{ color: "#059669" }}>
                {t('debts.fullyRepaid')}
              </Text>
            </View>
          )}
        </View>
      )}
    </View>
  );
}

export function ClaimsSection() {
  const { data: claims = [], isLoading } = useClaims();
  const { t } = useTranslation();
  const [showClosed, setShowClosed] = useState(false);

  if (isLoading) {
    return (
      <View className="py-4 items-center">
        <ActivityIndicator size="small" color="#7c3aed" />
      </View>
    );
  }

  if (claims.length === 0) return null;

  const open = claims.filter((d) => d.closedAt === null);
  const closed = claims.filter((d) => d.closedAt !== null);

  return (
    <View className="mb-2">
      <View className="flex-row items-center px-4 py-3">
        <Ionicons name="cash-outline" size={18} color="#7c3aed" style={{ marginRight: 8 }} />
        <Text className="text-sm font-semibold text-gray-800">{t('debts.claims')}</Text>
      </View>

      {open.map((debt) => (
        <ClaimCard key={debt.id} debt={debt} />
      ))}

      {closed.length > 0 && (
        <>
          <Pressable
            onPress={() => setShowClosed((v) => !v)}
            className="flex-row items-center gap-1 mx-4 mb-2"
          >
            <Text className="text-xs text-gray-400">
              {t(showClosed ? 'debts.toggleClosed_hide' : 'debts.toggleClosed_show', { count: closed.length, plural: closed.length === 1 ? '' : 'r' })}
            </Text>
            <Ionicons name={showClosed ? "chevron-up" : "chevron-down"} size={12} color="#9ca3af" />
          </Pressable>
          {showClosed && closed.map((debt) => <ClaimCard key={debt.id} debt={debt} />)}
        </>
      )}
    </View>
  );
}
