'use client';

import { useState, useEffect } from 'react';
import {
  Box,
  Typography,
  Grid,
  Paper,
  Button,
  Avatar,
  Chip,
  CircularProgress,
  Alert,
  IconButton,
  Divider,
  Snackbar,
  Container,
  List,
  ListItem,
  ListItemAvatar,
  ListItemText,
  Card,
  CardContent,
} from '@mui/material';
import { PersonAdd, ContentCopy, People, Delete, GroupAdd } from '@mui/icons-material';
import { useAuth } from '@/lib/auth/AuthContext';
import { AppShell } from '@/components/layouts/AppShell/AppShell';
import { ProtectedRoute } from '@/components/common/ProtectedRoute';
import { familiesApi, Family, FamilyMember, InviteMemberData, JoinFamilyData } from '@/lib/api/families';
import { InviteMemberDialog } from '@/components/family/InviteMemberDialog';
import { JoinFamilyDialog } from '@/components/family/JoinFamilyDialog';
import { RemoveMemberDialog } from '@/components/family/RemoveMemberDialog';
import { motion } from 'framer-motion';
import { useTranslation } from '@/hooks/useTranslation';

export default function FamilyPage() {
  const { t } = useTranslation('family');
  const { user, refreshUser } = useAuth();
  const [family, setFamily] = useState<Family | null>(null);
  const [members, setMembers] = useState<FamilyMember[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string>('');
  const [inviteDialogOpen, setInviteDialogOpen] = useState(false);
  const [joinDialogOpen, setJoinDialogOpen] = useState(false);
  const [removeDialogOpen, setRemoveDialogOpen] = useState(false);
  const [memberToRemove, setMemberToRemove] = useState<FamilyMember | null>(null);
  const [actionLoading, setActionLoading] = useState(false);
  const [snackbar, setSnackbar] = useState({ open: false, message: '' });

  // Get familyId from user
  const familyId = user?.families?.[0]?.familyId;

  useEffect(() => {
    if (familyId) {
      fetchFamilyData();
    } else {
      setLoading(false);
      setError(t('messages.noFamilyFound'));
    }
  }, [familyId]);

  const fetchFamilyData = async () => {
    if (!familyId) return;

    try {
      setLoading(true);
      setError('');
      const [familyData, membersData] = await Promise.all([
        familiesApi.getFamily(familyId),
        familiesApi.getFamilyMembers(familyId),
      ]);
      setFamily(familyData);
      setMembers(membersData);
    } catch (err: any) {
      console.error('Failed to fetch family data:', err);
      setError(err.response?.data?.message || t('messages.failedToLoad'));
    } finally {
      setLoading(false);
    }
  };

  const handleCopyCode = async () => {
    if (!family?.shareCode) return;

    try {
      await navigator.clipboard.writeText(family.shareCode);
      setSnackbar({ open: true, message: t('messages.shareCodeCopied') });
    } catch (err) {
      setSnackbar({ open: true, message: t('messages.shareCodeCopyFailed') });
    }
  };

  const handleInviteMember = async (data: InviteMemberData) => {
    if (!familyId) {
      throw new Error(t('messages.noFamilyId'));
    }

    try {
      setActionLoading(true);
      await familiesApi.inviteMember(familyId, data);
      setSnackbar({ open: true, message: t('messages.invitationSent') });
      await fetchFamilyData();
      setInviteDialogOpen(false);
    } catch (err: any) {
      console.error('Failed to invite member:', err);
      throw new Error(err.response?.data?.message || t('messages.failedToInvite'));
    } finally {
      setActionLoading(false);
    }
  };

  const handleJoinFamily = async (data: JoinFamilyData) => {
    try {
      setActionLoading(true);
      await familiesApi.joinFamily(data);
      setSnackbar({ open: true, message: t('messages.joinedFamily') });
      await refreshUser();
      await fetchFamilyData();
      setJoinDialogOpen(false);
    } catch (err: any) {
      console.error('Failed to join family:', err);
      throw new Error(err.response?.data?.message || t('messages.failedToJoin'));
    } finally {
      setActionLoading(false);
    }
  };

  const handleRemoveClick = (member: FamilyMember) => {
    setMemberToRemove(member);
    setRemoveDialogOpen(true);
  };

  const handleRemoveConfirm = async () => {
    if (!familyId || !memberToRemove) return;

    try {
      setActionLoading(true);
      await familiesApi.removeMember(familyId, memberToRemove.userId);
      setSnackbar({ open: true, message: t('messages.memberRemoved') });
      await fetchFamilyData();
      setRemoveDialogOpen(false);
      setMemberToRemove(null);
    } catch (err: any) {
      console.error('Failed to remove member:', err);
      setError(err.response?.data?.message || t('messages.failedToRemove'));
    } finally {
      setActionLoading(false);
    }
  };

  const getRoleColor = (role: string): 'primary' | 'secondary' | 'default' | 'success' | 'warning' | 'info' => {
    switch (role) {
      case 'parent':
        return 'primary';
      case 'caregiver':
        return 'secondary';
      case 'viewer':
        return 'info';
      default:
        return 'default';
    }
  };

  const isCurrentUser = (userId: string) => {
    return user?.id === userId;
  };

  return (
    <ProtectedRoute>
      <AppShell>
        <Container maxWidth="md" sx={{ px: { xs: 2, sm: 3 }, py: 3 }}>
          <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 4 }}>
            <Box>
              <Typography variant="h4" component="h1" fontWeight="600">
                {t('pageTitle')}
              </Typography>
              <Typography variant="body2" color="text.secondary">
                {t('pageSubtitle')}
              </Typography>
            </Box>
            <Box sx={{ display: 'flex', gap: 2 }}>
              <Button
                variant="outlined"
                startIcon={<GroupAdd />}
                onClick={() => setJoinDialogOpen(true)}
                disabled={loading}
                sx={{ borderRadius: 2, textTransform: 'none' }}
              >
                {t('buttons.joinFamily')}
              </Button>
              <Button
                variant="contained"
                startIcon={<PersonAdd />}
                onClick={() => setInviteDialogOpen(true)}
                disabled={loading || !familyId}
                sx={{ borderRadius: 2, textTransform: 'none' }}
              >
                {t('buttons.inviteMember')}
              </Button>
            </Box>
          </Box>

          {error && (
            <Alert severity="error" sx={{ mb: 3 }} onClose={() => setError('')}>
              {error}
            </Alert>
          )}

          {loading ? (
            <Box sx={{ display: 'flex', justifyContent: 'center', py: 8 }}>
              <CircularProgress />
            </Box>
          ) : (
            <Grid container spacing={4}>
              {/* Family Share Code */}
              {family && (
                <Grid item xs={12} md={6}>
                  <Paper elevation={0} sx={{ p: 3, borderRadius: 3, bgcolor: 'background.paper' }}>
                    <Typography variant="h6" sx={{ mb: 2, fontWeight: 600 }}>
                      {t('shareCode.title')}
                    </Typography>
                    <Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
                      {t('shareCode.description')}
                    </Typography>
                    <Box sx={{ display: 'flex', gap: 2, alignItems: 'center' }}>
                      <Chip
                        label={family.shareCode}
                        sx={{
                          px: 3,
                          py: 1,
                          fontSize: '1.25rem',
                          fontWeight: 600,
                          bgcolor: 'primary.light',
                          color: 'primary.main'
                        }}
                      />
                      <Button
                        variant="outlined"
                        startIcon={<ContentCopy />}
                        onClick={handleCopyCode}
                        sx={{ borderRadius: 2, textTransform: 'none' }}
                      >
                        {t('buttons.copyCode')}
                      </Button>
                    </Box>
                  </Paper>
                </Grid>
              )}

              {/* Family Members */}
              <Grid item xs={12} md={6}>
                <Paper elevation={0} sx={{ p: 3, borderRadius: 3, bgcolor: 'background.paper' }}>
                  <Typography variant="h6" sx={{ mb: 3, fontWeight: 600 }}>
                    {t('members.title', { count: members.length })}
                  </Typography>

                    {members.length === 0 ? (
                      <Box sx={{ textAlign: 'center', py: 4 }}>
                        <People sx={{ fontSize: 48, color: 'text.secondary', mb: 2 }} />
                        <Typography variant="body2" color="text.secondary" gutterBottom>
                          {t('members.noMembers')}
                        </Typography>
                        <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
                          {t('members.noMembersDescription')}
                        </Typography>
                        <Button
                          variant="outlined"
                          startIcon={<PersonAdd />}
                          onClick={() => setInviteDialogOpen(true)}
                        >
                          {t('buttons.inviteFirstMember')}
                        </Button>
                      </Box>
                    ) : (
                      <List sx={{ p: 0 }}>
                        {members.map((member, index) => {
                          const memberName = member.user?.name || t('placeholders.unknownUser');
                          return (
                            <motion.div
                              key={member.id}
                              initial={{ opacity: 0, y: 10 }}
                              animate={{ opacity: 1, y: 0 }}
                              transition={{ duration: 0.2, delay: index * 0.05 }}
                            >
                              <ListItem
                                sx={{
                                  px: 2,
                                  py: 1.5,
                                  borderRadius: 2,
                                  mb: 1,
                                  bgcolor: 'background.default'
                                }}
                              >
                                <ListItemAvatar>
                                  <Avatar sx={{ bgcolor: isCurrentUser(member.userId) ? 'primary.main' : 'secondary.main' }}>
                                    {memberName[0]}
                                  </Avatar>
                                </ListItemAvatar>
                                <ListItemText
                                  primary={
                                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                                      <Typography variant="body1" fontWeight={500}>
                                        {memberName}
                                      </Typography>
                                      {isCurrentUser(member.userId) && (
                                        <Chip label={t('members.youLabel')} size="small" color="success" />
                                      )}
                                    </Box>
                                  }
                                  secondary={member.user?.email || t('placeholders.noEmail')}
                                  primaryTypographyProps={{ fontWeight: 500 }}
                                />
                                <Chip
                                  label={t(`roles.${member.role}`)}
                                  size="small"
                                  color={getRoleColor(member.role)}
                                  sx={{ borderRadius: 1, mr: 1 }}
                                />
                                {!isCurrentUser(member.userId) && (
                                  <IconButton
                                    size="small"
                                    onClick={() => handleRemoveClick(member)}
                                    color="error"
                                    aria-label={t('members.removeAriaLabel', { name: memberName })}
                                  >
                                    <Delete fontSize="small" />
                                  </IconButton>
                                )}
                              </ListItem>
                            </motion.div>
                          );
                        })}
                      </List>
                    )}
                  </Paper>
              </Grid>
            </Grid>
          )}
        </Container>

        <InviteMemberDialog
          open={inviteDialogOpen}
          onClose={() => setInviteDialogOpen(false)}
          onSubmit={handleInviteMember}
          isLoading={actionLoading}
        />

        <JoinFamilyDialog
          open={joinDialogOpen}
          onClose={() => setJoinDialogOpen(false)}
          onSubmit={handleJoinFamily}
          isLoading={actionLoading}
        />

        <RemoveMemberDialog
          open={removeDialogOpen}
          onClose={() => setRemoveDialogOpen(false)}
          onConfirm={handleRemoveConfirm}
          memberName={memberToRemove?.user?.name || ''}
          isLoading={actionLoading}
        />

        <Snackbar
          open={snackbar.open}
          autoHideDuration={4000}
          onClose={() => setSnackbar({ ...snackbar, open: false })}
          message={snackbar.message}
        />
      </AppShell>
    </ProtectedRoute>
  );
}
