'use client';

import { useState, useEffect } from 'react';
import {
  Box,
  Paper,
  Button,
  Typography,
  IconButton,
  Chip,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  FormControlLabel,
  Switch,
  Alert,
  Tooltip,
} from '@mui/material';
import { DataGrid, GridColDef } from '@mui/x-data-grid';
import {
  Add,
  Edit,
  Delete,
  ContentCopy,
  Refresh,
} from '@mui/icons-material';
import { format } from 'date-fns';
import AdminLayout from '@/components/AdminLayout';
import apiClient from '@/lib/api-client';

interface InviteCode {
  id: string;
  code: string;
  uses: number;
  maxUses: number | null;
  expiresAt: string | null;
  createdAt: string;
  createdBy: string;
  isActive: boolean;
  metadata?: any;
}

export default function InviteCodesPage() {
  const [inviteCodes, setInviteCodes] = useState<InviteCode[]>([]);
  const [loading, setLoading] = useState(true);
  const [openDialog, setOpenDialog] = useState(false);
  const [editingCode, setEditingCode] = useState<InviteCode | null>(null);
  const [copied, setCopied] = useState<string | null>(null);

  // Form state
  const [formData, setFormData] = useState({
    code: '',
    maxUses: '',
    hasExpiry: false,
    expiresAt: '',
    description: '',
  });

  const fetchInviteCodes = async () => {
    setLoading(true);
    try {
      const data = await apiClient.getInviteCodes();
      setInviteCodes(data.codes || []);
    } catch (error) {
      console.error('Failed to fetch invite codes:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchInviteCodes();
  }, []);

  const generateRandomCode = () => {
    const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
    let code = '';
    for (let i = 0; i < 8; i++) {
      code += chars.charAt(Math.floor(Math.random() * chars.length));
      if (i === 3) code += '-';
    }
    setFormData({ ...formData, code });
  };

  const handleCopyCode = (code: string) => {
    navigator.clipboard.writeText(code);
    setCopied(code);
    setTimeout(() => setCopied(null), 2000);
  };

  const handleSubmit = async () => {
    try {
      const payload = {
        code: formData.code,
        maxUses: formData.maxUses ? parseInt(formData.maxUses) : undefined,
        expiresAt: formData.hasExpiry ? formData.expiresAt : undefined,
        metadata: formData.description ? { description: formData.description } : undefined,
      };

      if (editingCode) {
        await apiClient.updateInviteCode(editingCode.id, payload);
      } else {
        await apiClient.createInviteCode(payload);
      }

      fetchInviteCodes();
      handleCloseDialog();
    } catch (error) {
      console.error('Failed to save invite code:', error);
    }
  };

  const handleDelete = async (id: string) => {
    if (confirm('Are you sure you want to delete this invite code?')) {
      try {
        await apiClient.deleteInviteCode(id);
        fetchInviteCodes();
      } catch (error) {
        console.error('Failed to delete invite code:', error);
      }
    }
  };

  const handleCloseDialog = () => {
    setOpenDialog(false);
    setEditingCode(null);
    setFormData({
      code: '',
      maxUses: '',
      hasExpiry: false,
      expiresAt: '',
      description: '',
    });
  };

  const columns: GridColDef[] = [
    {
      field: 'code',
      headerName: 'Code',
      width: 150,
      renderCell: (params) => (
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <Typography variant="body2" sx={{ fontFamily: 'monospace', fontWeight: 500 }}>
            {params.value}
          </Typography>
          <Tooltip title={copied === params.value ? 'Copied!' : 'Copy code'}>
            <IconButton size="small" onClick={() => handleCopyCode(params.value)}>
              <ContentCopy fontSize="small" />
            </IconButton>
          </Tooltip>
        </Box>
      ),
    },
    {
      field: 'status',
      headerName: 'Status',
      width: 120,
      renderCell: (params) => {
        const isExpired = params.row.expiresAt && new Date(params.row.expiresAt) < new Date();
        const isMaxedOut = params.row.maxUses && params.row.uses >= params.row.maxUses;

        if (!params.row.isActive) {
          return <Chip label="Inactive" size="small" color="default" />;
        } else if (isExpired) {
          return <Chip label="Expired" size="small" color="error" />;
        } else if (isMaxedOut) {
          return <Chip label="Used Up" size="small" color="warning" />;
        }
        return <Chip label="Active" size="small" color="success" />;
      },
    },
    {
      field: 'uses',
      headerName: 'Uses',
      width: 100,
      renderCell: (params) => (
        <Typography variant="body2">
          {params.value.toLocaleString()} / {params.row.maxUses?.toLocaleString() || '∞'}
        </Typography>
      ),
    },
    {
      field: 'expiresAt',
      headerName: 'Expires',
      width: 150,
      renderCell: (params) => (
        <Typography variant="body2">
          {params.value ? format(new Date(params.value), 'MMM dd, yyyy') : 'Never'}
        </Typography>
      ),
    },
    {
      field: 'createdAt',
      headerName: 'Created',
      width: 150,
      renderCell: (params) => (
        <Typography variant="body2">
          {format(new Date(params.value), 'MMM dd, yyyy')}
        </Typography>
      ),
    },
    {
      field: 'actions',
      headerName: 'Actions',
      width: 100,
      sortable: false,
      renderCell: (params) => (
        <Box>
          <IconButton size="small" onClick={() => {
            setEditingCode(params.row);
            setFormData({
              code: params.row.code,
              maxUses: params.row.maxUses?.toString() || '',
              hasExpiry: !!params.row.expiresAt,
              expiresAt: params.row.expiresAt || '',
              description: params.row.metadata?.description || '',
            });
            setOpenDialog(true);
          }}>
            <Edit fontSize="small" />
          </IconButton>
          <IconButton size="small" onClick={() => handleDelete(params.row.id)} color="error">
            <Delete fontSize="small" />
          </IconButton>
        </Box>
      ),
    },
  ];

  return (
    <AdminLayout>
      <Box>
        <Box sx={{ mb: 3, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <Typography variant="h5" fontWeight={600}>
            Invite Codes Management
          </Typography>
          <Box sx={{ display: 'flex', gap: 1 }}>
            <Button
              startIcon={<Refresh />}
              onClick={fetchInviteCodes}
              variant="outlined"
            >
              Refresh
            </Button>
            <Button
              startIcon={<Add />}
              variant="contained"
              onClick={() => setOpenDialog(true)}
            >
              Create Invite Code
            </Button>
          </Box>
        </Box>

        <Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(250px, 1fr))', gap: 3, mb: 3 }}>
          <Paper sx={{ p: 2 }}>
            <Typography variant="body2" color="text.secondary" gutterBottom>
              Total Codes
            </Typography>
            <Typography variant="h4">{inviteCodes.length.toLocaleString()}</Typography>
          </Paper>
          <Paper sx={{ p: 2 }}>
            <Typography variant="body2" color="text.secondary" gutterBottom>
              Active Codes
            </Typography>
            <Typography variant="h4">
              {inviteCodes.filter(c => c.isActive).length.toLocaleString()}
            </Typography>
          </Paper>
          <Paper sx={{ p: 2 }}>
            <Typography variant="body2" color="text.secondary" gutterBottom>
              Total Uses
            </Typography>
            <Typography variant="h4">
              {inviteCodes.reduce((sum, c) => sum + c.uses, 0).toLocaleString()}
            </Typography>
          </Paper>
          <Paper sx={{ p: 2 }}>
            <Typography variant="body2" color="text.secondary" gutterBottom>
              Available
            </Typography>
            <Typography variant="h4">
              {inviteCodes.filter(c => {
                const isExpired = c.expiresAt && new Date(c.expiresAt) < new Date();
                const isMaxedOut = c.maxUses && c.uses >= c.maxUses;
                return c.isActive && !isExpired && !isMaxedOut;
              }).length.toLocaleString()}
            </Typography>
          </Paper>
        </Box>

        <Paper sx={{ p: 2 }}>
          <DataGrid
            rows={inviteCodes}
            columns={columns}
            loading={loading}
            pageSizeOptions={[10, 25, 50]}
            initialState={{
              pagination: { paginationModel: { pageSize: 10 } },
            }}
            disableRowSelectionOnClick
            autoHeight
          />
        </Paper>

        <Dialog open={openDialog} onClose={handleCloseDialog} maxWidth="sm" fullWidth>
          <DialogTitle>
            {editingCode ? 'Edit Invite Code' : 'Create New Invite Code'}
          </DialogTitle>
          <DialogContent>
            <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2, pt: 1 }}>
              <Box sx={{ display: 'flex', gap: 1 }}>
                <TextField
                  label="Invite Code"
                  value={formData.code}
                  onChange={(e) => setFormData({ ...formData, code: e.target.value })}
                  fullWidth
                  required
                  placeholder="ABCD-1234"
                />
                <Button onClick={generateRandomCode} variant="outlined">
                  Generate
                </Button>
              </Box>

              <TextField
                label="Max Uses (leave empty for unlimited)"
                type="number"
                value={formData.maxUses}
                onChange={(e) => setFormData({ ...formData, maxUses: e.target.value })}
                fullWidth
                InputProps={{ inputProps: { min: 1 } }}
              />

              <FormControlLabel
                control={
                  <Switch
                    checked={formData.hasExpiry}
                    onChange={(e) => setFormData({ ...formData, hasExpiry: e.target.checked })}
                  />
                }
                label="Set expiration date"
              />

              {formData.hasExpiry && (
                <TextField
                  label="Expires At"
                  type="datetime-local"
                  value={formData.expiresAt}
                  onChange={(e) => setFormData({ ...formData, expiresAt: e.target.value })}
                  fullWidth
                  InputLabelProps={{ shrink: true }}
                />
              )}

              <TextField
                label="Description (optional)"
                value={formData.description}
                onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                fullWidth
                multiline
                rows={2}
                placeholder="e.g., Beta testers group"
              />

              <Alert severity="info">
                Share this code with users to allow them to register.
                The code can be used during the signup process.
              </Alert>
            </Box>
          </DialogContent>
          <DialogActions>
            <Button onClick={handleCloseDialog}>Cancel</Button>
            <Button onClick={handleSubmit} variant="contained" disabled={!formData.code}>
              {editingCode ? 'Update' : 'Create'}
            </Button>
          </DialogActions>
        </Dialog>
      </Box>
    </AdminLayout>
  );
}