'use client';

import { JoinRequestItem } from '@/components/leagues/JoinRequestItem';
import { JoinRequestList } from '@/components/leagues/JoinRequestList';
import { MinimalEmptyState } from '@/components/shared/state/EmptyState';
import { useApproveJoinRequest } from "@/hooks/team/useApproveJoinRequest";
import { useRejectJoinRequest } from "@/hooks/team/useRejectJoinRequest";
import { useTeamJoinRequests } from "@/hooks/team/useTeamJoinRequests";
import { useUpdateTeam } from "@/hooks/team/useUpdateTeam";
import type { TeamJoinRequestViewModel } from '@/lib/view-models/TeamJoinRequestViewModel';
import { Button } from '@/ui/Button';
import { Card } from '@/ui/Card';
import { DangerZone } from '@/ui/DangerZone';
import { Heading } from '@/ui/Heading';
import { Input } from '@/ui/Input';
import { Stack } from '@/ui/primitives/Stack';
import { Text } from '@/ui/Text';
import { TextArea } from '@/ui/TextArea';
import { useState } from 'react';

interface TeamAdminProps {
  team: {
    id: string;
    name: string;
    tag: string;
    description?: string;
    ownerId: string;
  };
  onUpdate: () => void;
}

export function TeamAdmin({ team, onUpdate }: TeamAdminProps) {
  const [editMode, setEditMode] = useState(false);
  const [editedTeam, setEditedTeam] = useState({
    name: team.name,
    tag: team.tag,
    description: team.description || '',
  });

  // Use hooks for data fetching
  const { data: joinRequests = [], isLoading: loading } = useTeamJoinRequests(
    team.id,
    team.ownerId,
    true
  );

  // Use hooks for mutations
  const updateTeamMutation = useUpdateTeam({
    onSuccess: () => {
      setEditMode(false);
      onUpdate();
    },
    onError: (error) => {
      alert(error instanceof Error ? error.message : 'Failed to update team');
    },
  });

  const approveJoinRequestMutation = useApproveJoinRequest({
    onSuccess: () => {
      onUpdate();
    },
    onError: (error) => {
      alert(error instanceof Error ? error.message : 'Failed to approve request');
    },
  });

  const rejectJoinRequestMutation = useRejectJoinRequest({
    onSuccess: () => {
      onUpdate();
    },
    onError: (error) => {
      alert(error instanceof Error ? error.message : 'Failed to reject request');
    },
  });

  const handleApprove = () => {
    // Note: The current API doesn't support approving specific requests
    // This would need the requestId to be passed to the service
    approveJoinRequestMutation.mutate();
  };

  const handleReject = () => {
    // Note: The current API doesn't support rejecting specific requests
    // This would need the requestId to be passed to the service
    rejectJoinRequestMutation.mutate();
  };

  const handleSaveChanges = () => {
    updateTeamMutation.mutate({
      teamId: team.id,
      input: {
        name: editedTeam.name,
        tag: editedTeam.tag,
        description: editedTeam.description,
      },
    });
  };

  return (
    <Stack gap={6}>
      <Card>
        <Stack display="flex" alignItems="center" justifyContent="between" mb={6}>
          <Heading level={3}>Team Settings</Heading>
          {!editMode && (
            <Button variant="secondary" onClick={() => setEditMode(true)}>
              Edit Details
            </Button>
          )}
        </Stack>

        {editMode ? (
          <Stack gap={4}>
            <Stack>
              <Text as="label" size="sm" weight="medium" color="text-gray-400" block mb={2}>
                Team Name
              </Text>
              <Input
                type="text"
                value={editedTeam.name}
                onChange={(e) => setEditedTeam({ ...editedTeam, name: e.target.value })}
              />
            </Stack>

            <Stack>
              <Text as="label" size="sm" weight="medium" color="text-gray-400" block mb={2}>
                Team Tag
              </Text>
              <Input
                type="text"
                value={editedTeam.tag}
                onChange={(e) => setEditedTeam({ ...editedTeam, tag: e.target.value })}
                maxLength={4}
              />
              <Text size="xs" color="text-gray-500" block mt={1}>Max 4 characters</Text>
            </Stack>

            <TextArea
              label="Description"
              rows={4}
              value={editedTeam.description}
              onChange={(e) => setEditedTeam({ ...editedTeam, description: e.target.value })}
            />

            <Stack direction="row" gap={2}>
              <Button variant="primary" onClick={handleSaveChanges} disabled={updateTeamMutation.isPending}>
                {updateTeamMutation.isPending ? 'Saving...' : 'Save Changes'}
              </Button>
              <Button
                variant="secondary"
                onClick={() => {
                  setEditMode(false);
                  setEditedTeam({
                    name: team.name,
                    tag: team.tag,
                    description: team.description || '',
                  });
                }}
              >
                Cancel
              </Button>
            </Stack>
          </Stack>
        ) : (
          <Stack gap={4}>
            <Stack>
              <Text size="sm" color="text-gray-400" block>Team Name</Text>
              <Text color="text-white" weight="medium" block>{team.name}</Text>
            </Stack>
            <Stack>
              <Text size="sm" color="text-gray-400" block>Team Tag</Text>
              <Text color="text-white" weight="medium" block>{team.tag}</Text>
            </Stack>
            <Stack>
              <Text size="sm" color="text-gray-400" block>Description</Text>
              <Text color="text-white" block>{team.description}</Text>
            </Stack>
          </Stack>
        )}
      </Card>

      <Card>
        <Heading level={3} mb={6}>Join Requests</Heading>

        {loading ? (
          <Stack textAlign="center" py={8}>
            <Text color="text-gray-400">Loading requests...</Text>
          </Stack>
        ) : joinRequests.length > 0 ? (
          <JoinRequestList>
            {joinRequests.map((request: TeamJoinRequestViewModel) => (
              <JoinRequestItem
                key={request.requestId}
                driverId={request.driverId}
                requestedAt={request.requestedAt}
                onApprove={() => handleApprove()}
                onReject={() => handleReject()}
                isApproving={approveJoinRequestMutation.isPending}
                isRejecting={rejectJoinRequestMutation.isPending}
              />
            ))}
          </JoinRequestList>
        ) : (
          <MinimalEmptyState
            title="No pending join requests"
            description="When drivers request to join your team, they will appear here."
          />
        )}
      </Card>

      <DangerZone
        title="Disband Team"
        description="Permanently delete this team. This action cannot be undone."
      >
        <Button variant="danger" disabled>
          Disband Team (Coming Soon)
        </Button>
      </DangerZone>
    </Stack>
  );
}
