'use client';

import { useState, useEffect } from 'react';
import {
  Box,
  Typography,
  Grid,
  Card,
  CardContent,
  Button,
  Avatar,
  Chip,
  CircularProgress,
  Alert,
  IconButton,
  Divider,
  Snackbar,
} 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';

export default function FamilyPage() {
  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('No family found. Please complete onboarding first.');
    }
  }, [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 || 'Failed to load family information');
    } finally {
      setLoading(false);
    }
  };

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

    try {
      await navigator.clipboard.writeText(family.shareCode);
      setSnackbar({ open: true, message: 'Share code copied to clipboard!' });
    } catch (err) {
      setSnackbar({ open: true, message: 'Failed to copy share code' });
    }
  };

  const handleInviteMember = async (data: InviteMemberData) => {
    if (!familyId) {
      throw new Error('No family ID found');
    }

    try {
      setActionLoading(true);
      await familiesApi.inviteMember(familyId, data);
      setSnackbar({ open: true, message: 'Invitation sent successfully!' });
      await fetchFamilyData();
      setInviteDialogOpen(false);
    } catch (err: any) {
      console.error('Failed to invite member:', err);
      throw new Error(err.response?.data?.message || 'Failed to send invitation');
    } finally {
      setActionLoading(false);
    }
  };

  const handleJoinFamily = async (data: JoinFamilyData) => {
    try {
      setActionLoading(true);
      await familiesApi.joinFamily(data);
      setSnackbar({ open: true, message: 'Successfully joined family!' });
      await refreshUser();
      await fetchFamilyData();
      setJoinDialogOpen(false);
    } catch (err: any) {
      console.error('Failed to join family:', err);
      throw new Error(err.response?.data?.message || 'Failed to join family');
    } 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: 'Member removed successfully' });
      await fetchFamilyData();
      setRemoveDialogOpen(false);
      setMemberToRemove(null);
    } catch (err: any) {
      console.error('Failed to remove member:', err);
      setError(err.response?.data?.message || 'Failed to remove member');
    } 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>
        <Box>
          <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 4 }}>
            <Box>
              <Typography variant="h4" component="h1" fontWeight="600" gutterBottom>
                Family
              </Typography>
              <Typography variant="body1" color="text.secondary">
                Manage your family members and share access
              </Typography>
            </Box>
            <Box sx={{ display: 'flex', gap: 1 }}>
              <Button
                variant="outlined"
                startIcon={<GroupAdd />}
                onClick={() => setJoinDialogOpen(true)}
                disabled={loading}
              >
                Join Family
              </Button>
              <Button
                variant="contained"
                startIcon={<PersonAdd />}
                onClick={() => setInviteDialogOpen(true)}
                disabled={loading || !familyId}
              >
                Invite Member
              </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={3}>
              {/* Family Share Code */}
              {family && (
                <Grid item xs={12}>
                  <Card>
                    <CardContent>
                      <Typography variant="h6" component="h2" fontWeight="600" gutterBottom>
                        Family Share Code
                      </Typography>
                      <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
                        Share this code with family members to give them access to your family's data
                      </Typography>
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, flexWrap: 'wrap' }}>
                        <Chip
                          label={family.shareCode}
                          sx={{
                            fontSize: '1.1rem',
                            fontWeight: 600,
                            py: 2.5,
                            px: 1,
                          }}
                          color="primary"
                        />
                        <Button
                          variant="outlined"
                          startIcon={<ContentCopy />}
                          onClick={handleCopyCode}
                        >
                          Copy Code
                        </Button>
                      </Box>
                    </CardContent>
                  </Card>
                </Grid>
              )}

              {/* Family Members */}
              <Grid item xs={12}>
                <Card>
                  <CardContent>
                    <Typography variant="h6" fontWeight="600" gutterBottom sx={{ mb: 3 }}>
                      Family Members ({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>
                          No family members yet
                        </Typography>
                        <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
                          Invite family members to collaborate on child care
                        </Typography>
                        <Button
                          variant="outlined"
                          startIcon={<PersonAdd />}
                          onClick={() => setInviteDialogOpen(true)}
                        >
                          Invite First Member
                        </Button>
                      </Box>
                    ) : (
                      <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
                        {members.map((member, index) => {
                          const memberName = member.user?.name || 'Unknown User';
                          return (
                            <Box key={member.id} component="div">
                              <motion.div
                                initial={{ opacity: 0, y: 10 }}
                                animate={{ opacity: 1, y: 0 }}
                                transition={{ duration: 0.2, delay: index * 0.05 }}
                              >
                                <Box>
                                  {index > 0 && <Divider sx={{ mb: 2 }} />}
                                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
                                    <Avatar
                                      sx={{
                                        bgcolor: isCurrentUser(member.userId) ? 'primary.main' : 'secondary.main',
                                      }}
                                    >
                                      {memberName.charAt(0).toUpperCase()}
                                    </Avatar>
                                    <Box sx={{ flex: 1 }}>
                                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                                        <Typography variant="body1" fontWeight="600">
                                          {memberName}
                                        </Typography>
                                        {isCurrentUser(member.userId) && (
                                          <Chip label="You" size="small" color="success" />
                                        )}
                                      </Box>
                                      <Typography variant="body2" color="text.secondary">
                                        {member.user?.email || 'No email'}
                                      </Typography>
                                    </Box>
                                    <Chip
                                      label={member.role.charAt(0).toUpperCase() + member.role.slice(1)}
                                      color={getRoleColor(member.role)}
                                      size="small"
                                    />
                                    {!isCurrentUser(member.userId) && (
                                      <IconButton
                                        size="small"
                                        onClick={() => handleRemoveClick(member)}
                                        color="error"
                                        aria-label={`Remove ${memberName} from family`}
                                      >
                                        <Delete />
                                      </IconButton>
                                    )}
                                  </Box>
                                </Box>
                              </motion.div>
                            </Box>
                          );
                        })}
                      </Box>
                    )}
                  </CardContent>
                </Card>
              </Grid>
            </Grid>
          )}
        </Box>

        <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>
  );
}
