<template>
  <!-- Page Header -->
  <div class="mb-8">
    <Heading :level="1" class="text-3xl font-black text-gray-900 mb-2">
      {{ t('groupsPage.title', 'Your Households') }}
    </Heading>
    <p class="text-gray-600 text-lg">
      {{ t('groupsPage.subtitle', 'Manage your shared spaces and collaborate with others') }}
    </p>
  </div>

  <!-- Loading State -->
  <div v-if="isInitiallyLoading" class="flex justify-center items-center py-16">
    <div class="text-center">
      <Spinner size="lg" class="mb-4" />
      <p class="text-gray-600">{{ t('groupsPage.loadingText', 'Loading households...') }}</p>
    </div>
  </div>

  <!-- Error State -->
  <Alert v-else-if="fetchError" type="error" class="mb-6">
    <div class="flex items-center justify-between">
      <span>{{ fetchError }}</span>
      <Button size="sm" color="error" @click="() => fetchGroups(true)">
        {{ t('groupsPage.retryButton', 'Retry') }}
      </Button>
    </div>
  </Alert>

  <!-- Empty State -->
  <div v-else-if="!isInitiallyLoading && groups.length === 0" class="text-center py-16">
    <Card class="max-w-md mx-auto p-8 bg-white border-3 border-gray-900 shadow-[8px_8px_0px_0px_#111]">
      <div class="mb-6">
        <div class="w-16 h-16 mx-auto mb-4 bg-gray-100 rounded-full flex items-center justify-center">
          <svg class="w-8 h-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
              d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
          </svg>
        </div>
        <Heading :level="3" class="text-xl font-bold text-gray-900 mb-2">
          {{ t('groupsPage.emptyState.title', 'No Households Yet') }}
        </Heading>
        <p class="text-gray-600 mb-6">
          {{ t('groupsPage.emptyState.description', 'Create your first household or join an existing one!') }}
        </p>
      </div>
      <div class="space-y-3">
        <Button @click="openCreateDialog" class="w-full" size="lg">
          <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
          </svg>
          {{ t('groupsPage.emptyState.createButton', 'Create Household') }}
        </Button>
        <Button @click="openJoinDialog" variant="outline" class="w-full" size="lg">
          {{ t('groupsPage.emptyState.joinButton', 'Join with Invite Code') }}
        </Button>
      </div>
    </Card>
  </div>

  <!-- Groups Grid -->
  <div v-else class="space-y-6">
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
      <!-- Existing Groups -->
      <Card v-for="group in groups" :key="group.id"
        class="group-card cursor-pointer transition-all duration-200 hover:-translate-y-1 hover:shadow-[10px_10px_0px_0px_#111] bg-white border-3 border-gray-900 shadow-[6px_6px_0px_0px_#111]"
        @click="selectGroup(group)">
        <div class="p-6">
          <div class="flex items-start justify-between mb-4">
            <Heading :level="3" class="text-xl font-bold text-gray-900 leading-tight">
              {{ group.name }}
            </Heading>
            <div class="flex-shrink-0 ml-3">
              <div class="w-3 h-3 bg-green-400 rounded-full"></div>
            </div>
          </div>

          <div class="space-y-2 mb-4">
            <div class="flex items-center text-sm text-gray-600">
              <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                  d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197m13.5-9a2.5 2.5 0 11-5 0 2.5 2.5 0 015 0z" />
              </svg>
              {{ t('groupsPage.groupCard.memberCount', '{count} members', { count: group.member_count || 0 }) }}
            </div>
            <div class="flex items-center text-sm text-gray-600">
              <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                  d="M8 7V3a4 4 0 118 0v4m-4 8a2 2 0 11-4 0 2 2 0 014 0zM8 11V7a4 4 0 118 0v4" />
              </svg>
              {{ t('groupsPage.groupCard.createdDate', 'Created {date}', { date: formatDate(group.created_at) }) }}
            </div>
          </div>

          <div class="flex items-center justify-between">
            <Button size="sm" variant="outline" @click.stop="openCreateListDialog(group)" class="text-sm">
              <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
              </svg>
              {{ t('groupsPage.groupCard.newListButton', 'Quick List') }}
            </Button>

            <Button size="sm" @click.stop="selectGroup(group)">
              {{ t('groupsPage.groupCard.viewButton', 'View →') }}
            </Button>
          </div>
        </div>
      </Card>

      <!-- Create New Group Card -->
      <Card
        class="create-group-card cursor-pointer transition-all duration-200 hover:-translate-y-1 hover:shadow-[10px_10px_0px_0px_#111] bg-gradient-to-br from-blue-50 to-indigo-50 border-3 border-gray-900 shadow-[6px_6px_0px_0px_#111] border-dashed"
        @click="openCreateDialog">
        <div class="p-6 text-center">
          <div class="w-12 h-12 mx-auto mb-4 bg-blue-100 rounded-full flex items-center justify-center">
            <svg class="w-6 h-6 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
            </svg>
          </div>
          <Heading :level="3" class="text-lg font-bold text-gray-900 mb-2">
            {{ t('groupsPage.createCard.title', 'Create New Household') }}
          </Heading>
          <p class="text-sm text-gray-600">
            {{ t('groupsPage.createCard.description', 'Start fresh with a new shared space') }}
          </p>
        </div>
      </Card>
    </div>

    <!-- Quick Actions -->
    <div v-if="groups.length > 0" class="flex justify-center pt-4">
      <Button @click="openJoinDialog" variant="outline" size="lg">
        <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
            d="M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v1H3v-1z" />
        </svg>
        {{ t('groupsPage.joinButton', 'Join Another Household') }}
      </Button>
    </div>
  </div>

  <!-- Create Group Dialog -->
  <Dialog v-model="showCreateDialog" class="max-w-md">
    <div class="p-6">
      <Heading :level="2" class="text-xl font-bold text-gray-900 mb-4">
        {{ t('groupsPage.createDialog.title', 'Create New Household') }}
      </Heading>

      <form @submit.prevent="handleCreateGroup" class="space-y-4">
        <div>
          <label for="groupName" class="block text-sm font-medium text-gray-700 mb-2">
            {{ t('groupsPage.createDialog.groupNameLabel', 'Household Name') }}
          </label>
          <Input id="groupName" v-model="newGroupName"
            :placeholder="t('groupsPage.createDialog.groupNamePlaceholder', 'e.g., The Smiths, Apartment 4B, Our House')"
            required ref="groupNameInput" class="w-full" />
          <p v-if="createGroupFormError" class="mt-1 text-sm text-red-600">
            {{ createGroupFormError }}
          </p>
        </div>

        <div class="flex gap-3 pt-4">
          <Button type="button" variant="outline" class="flex-1" @click="showCreateDialog = false">
            {{ t('shared.cancel', 'Cancel') }}
          </Button>
          <Button type="submit" class="flex-1" :disabled="creatingGroup">
            <Spinner v-if="creatingGroup" size="sm" class="mr-2" />
            {{ t('groupsPage.createDialog.createButton', 'Create') }}
          </Button>
        </div>
      </form>
    </div>
  </Dialog>

  <!-- Join Group Dialog -->
  <Dialog v-model="showJoinDialog" class="max-w-md">
    <div class="p-6">
      <Heading :level="2" class="text-xl font-bold text-gray-900 mb-4">
        {{ t('groupsPage.joinDialog.title', 'Join Household') }}
      </Heading>

      <form @submit.prevent="handleJoinGroup" class="space-y-4">
        <div>
          <label for="inviteCode" class="block text-sm font-medium text-gray-700 mb-2">
            {{ t('groupsPage.joinDialog.codeLabel', 'Invite Code') }}
          </label>
          <Input id="inviteCode" v-model="inviteCodeToJoin"
            :placeholder="t('groupsPage.joinDialog.codePlaceholder', 'Enter invite code')" required
            ref="inviteCodeInput" class="w-full font-mono" />
          <p v-if="joinGroupFormError" class="mt-1 text-sm text-red-600">
            {{ joinGroupFormError }}
          </p>
          <p class="mt-2 text-sm text-gray-500">
            {{ joinDialogHelpText }}
          </p>
        </div>

        <div class="flex gap-3 pt-4">
          <Button type="button" variant="outline" class="flex-1" @click="showJoinDialog = false">
            {{ t('shared.cancel', 'Cancel') }}
          </Button>
          <Button type="submit" class="flex-1" :disabled="joiningGroup">
            <Spinner v-if="joiningGroup" size="sm" class="mr-2" />
            {{ t('groupsPage.joinDialog.joinButton', 'Join') }}
          </Button>
        </div>
      </form>
    </div>
  </Dialog>

  <!-- Create List Modal -->
  <CreateListModal v-model="showCreateListModal" :groups="availableGroupsForModal" @created="onListCreated" />
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import { apiClient, API_ENDPOINTS } from '@/services/api';
import { useStorage } from '@vueuse/core';
import { useNotificationStore } from '@/stores/notifications';
import { format } from 'date-fns';
import CreateListModal from '@/components/CreateListModal.vue';
import {
  Button,
  Dialog,
  Input,
  Heading,
  Spinner,
  Alert,
  Card,
} from '@/components/ui'

const { t } = useI18n<{ message: Record<string, string> }>();

interface Group {
  id: number;
  name: string;
  description?: string;
  member_count: number;
  created_at: string;
  updated_at: string;
}

const router = useRouter();
const notificationStore = useNotificationStore();

// State
const groups = ref<Group[]>([]);
const fetchError = ref<string | null>(null);
const isInitiallyLoading = ref(true);

// Create Dialog
const showCreateDialog = ref(false);
const newGroupName = ref('');
const creatingGroup = ref(false);
const createGroupFormError = ref<string | null>(null);
const groupNameInput = ref<HTMLInputElement | null>(null);

// Join Dialog
const showJoinDialog = ref(false);
const inviteCodeToJoin = ref('');
const joiningGroup = ref(false);
const joinGroupFormError = ref<string | null>(null);
const inviteCodeInput = ref<HTMLInputElement | null>(null);

// Create List Modal
const showCreateListModal = ref(false);
const availableGroupsForModal = ref<{ label: string; value: number; }[]>([]);

// Caching
const cachedGroups = useStorage<Group[]>('cached-groups', []);
const cachedTimestamp = useStorage<number>('cached-groups-timestamp', 0);
const CACHE_DURATION = 5 * 60 * 1000; // 5 minutes

// Initialize with cached data if available and fresh
const now = Date.now();
if (cachedGroups.value && (now - cachedTimestamp.value) < CACHE_DURATION) {
  groups.value = JSON.parse(JSON.stringify(cachedGroups.value));
  isInitiallyLoading.value = false;
}

const fetchGroups = async (isRetryAttempt = false) => {
  if (isRetryAttempt || (isInitiallyLoading.value && groups.value.length === 0)) {
    isInitiallyLoading.value = true;
  }
  fetchError.value = null;

  try {
    const response = await apiClient.get(API_ENDPOINTS.GROUPS.BASE);
    const freshGroups = response.data as Group[];
    groups.value = freshGroups;

    // Update cache
    cachedGroups.value = freshGroups;
    cachedTimestamp.value = Date.now();
  } catch (err: any) {
    let message = t('groupsPage.errors.fetchFailed', 'Failed to load households');
    if (err.response?.data?.detail) {
      message = err.response.data.detail;
    } else if (err.message) {
      message = err.message;
    }
    fetchError.value = message;
  } finally {
    isInitiallyLoading.value = false;
  }
};

const openCreateDialog = () => {
  newGroupName.value = '';
  createGroupFormError.value = null;
  showCreateDialog.value = true;
  nextTick(() => {
    groupNameInput.value?.focus();
  });
};

const openJoinDialog = () => {
  inviteCodeToJoin.value = '';
  joinGroupFormError.value = null;
  showJoinDialog.value = true;
  nextTick(() => {
    inviteCodeInput.value?.focus();
  });
};

const handleCreateGroup = async () => {
  if (!newGroupName.value.trim()) {
    createGroupFormError.value = t('groupsPage.errors.groupNameRequired', 'Household name is required');
    groupNameInput.value?.focus();
    return;
  }

  createGroupFormError.value = null;
  creatingGroup.value = true;

  try {
    const response = await apiClient.post(API_ENDPOINTS.GROUPS.BASE, {
      name: newGroupName.value.trim(),
    });

    const newGroup = response.data as Group;
    if (newGroup?.id && newGroup?.name) {
      groups.value.push(newGroup);
      showCreateDialog.value = false;

      notificationStore.addNotification({
        message: t('groupsPage.notifications.groupCreatedSuccess', 'Household "{groupName}" created successfully!', { groupName: newGroup.name }),
        type: 'success'
      });

      // Update cache
      cachedGroups.value = groups.value;
      cachedTimestamp.value = Date.now();
    } else {
      throw new Error(t('groupsPage.errors.invalidDataFromServer', 'Invalid response from server'));
    }
  } catch (error: any) {
    const message = error.response?.data?.detail ||
      (error instanceof Error ? error.message : t('groupsPage.errors.createFailed', 'Failed to create household'));
    createGroupFormError.value = message;
    notificationStore.addNotification({ message, type: 'error' });
  } finally {
    creatingGroup.value = false;
  }
};

const handleJoinGroup = async () => {
  if (!inviteCodeToJoin.value.trim()) {
    joinGroupFormError.value = t('groupsPage.errors.inviteCodeRequired', 'Invite code is required');
    inviteCodeInput.value?.focus();
    return;
  }

  joinGroupFormError.value = null;
  joiningGroup.value = true;

  try {
    const response = await apiClient.post(
      API_ENDPOINTS.INVITES.ACCEPT(inviteCodeToJoin.value.trim()),
      { code: inviteCodeToJoin.value.trim() }
    );

    const joinedGroup = response.data as Group;

    // Add to groups if not already present
    if (!groups.value.find(g => g.id === joinedGroup.id)) {
      groups.value.push(joinedGroup);
    }

    showJoinDialog.value = false;
    notificationStore.addNotification({
      message: t('groupsPage.notifications.joinSuccessNamed', 'Successfully joined "{groupName}"!', { groupName: joinedGroup.name }),
      type: 'success'
    });

    // Update cache
    cachedGroups.value = groups.value;
    cachedTimestamp.value = Date.now();
  } catch (error: any) {
    const message = error.response?.data?.detail ||
      (error instanceof Error ? error.message : t('groupsPage.errors.joinFailed', 'Failed to join household'));
    joinGroupFormError.value = message;
    notificationStore.addNotification({ message, type: 'error' });
  } finally {
    joiningGroup.value = false;
  }
};

const selectGroup = (group: Group) => {
  router.push(`/groups/${group.id}`);
};

const openCreateListDialog = (group: Group) => {
  availableGroupsForModal.value = [{
    label: group.name,
    value: group.id
  }];
  showCreateListModal.value = true;
};

const onListCreated = (newList: any) => {
  notificationStore.addNotification({
    message: t('groupsPage.notifications.listCreatedSuccess', 'List "{listName}" created successfully!', { listName: newList.name }),
    type: 'success'
  });
  // Optionally refresh groups if needed
};

const formatDate = (dateString: string) => {
  return format(new Date(dateString), 'MMM d, yyyy');
};

const joinDialogHelpText = computed(() => {
  return t('groupsPage.joinDialog.helpText', 'Ask a household member for their invite code or scan their QR code.');
});

onMounted(() => {
  fetchGroups();
});
</script>

<style scoped>
.group-card:hover {
  transform: translateY(-2px);
}

.create-group-card:hover {
  transform: translateY(-2px);
}

.container {
  max-width: 1200px;
}
</style>