'use client'

import Loading from '@/components/layout/shared/Loading'
import { useCampaignById, useCampaignRulesByCampaignId } from '@/services/queries/campaign'
import { CampaignRule, RewardType, RuleType } from '@/types/services/campaign'
import { formatCurrency } from '@/utils/transform'
import {
  Avatar,
  Card,
  CardHeader,
  CardContent,
  Chip,
  Typography,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  Box,
  Divider,
  Button,
  IconButton,
  Tooltip,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  DialogContentText
} from '@mui/material'
// Using Tabler icons instead of Material-UI icons
import { useParams } from 'next/navigation'
import { useState } from 'react'

const CampaignDetailContent = () => {
  const params = useParams()

  // State for dialogs
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
  const [selectedRuleId, setSelectedRuleId] = useState<string | null>(null)
  const [selectedRule, setSelectedRule] = useState<CampaignRule | null>(null)

  const { data: campaign, isLoading, error } = useCampaignById(params?.id as string)
  const { data: rules, isLoading: rulesLoading, error: rulesError } = useCampaignRulesByCampaignId(params?.id as string)

  if (isLoading) return <Loading />

  // Action handlers
  const handleAddRule = () => {
    // TODO: Implement add rule functionality
    // Could open a modal/form or navigate to add rule page
    console.log('Add new rule for campaign:', params?.id)
  }

  const handleEditRule = (rule: CampaignRule) => {
    // TODO: Implement edit rule functionality
    // Could open a modal/form or navigate to edit rule page
    console.log('Edit rule:', rule.id)
    setSelectedRule(rule)
    // You might want to open an edit modal here
  }

  const handleDeleteRule = (rule: CampaignRule) => {
    setSelectedRule(rule)
    setSelectedRuleId(rule.id)
    setDeleteDialogOpen(true)
  }

  const confirmDeleteRule = async () => {
    if (selectedRuleId) {
      try {
        // TODO: Implement actual delete API call
        console.log('Deleting rule:', selectedRuleId)
        // await deleteRuleMutation.mutateAsync(selectedRuleId)

        // Close dialog and reset state
        setDeleteDialogOpen(false)
        setSelectedRuleId(null)
        setSelectedRule(null)

        // Show success message or refresh data
      } catch (error) {
        console.error('Failed to delete rule:', error)
        // Handle error (show toast, etc.)
      }
    }
  }

  const cancelDelete = () => {
    setDeleteDialogOpen(false)
    setSelectedRuleId(null)
    setSelectedRule(null)
  }

  // Helper function to format rule type display
  const formatRuleType = (ruleType: RuleType) => {
    const ruleTypeLabels: Record<RuleType, string> = {
      TIER: 'Tier Based',
      SPEND: 'Spending Amount',
      PRODUCT: 'Product Based',
      CATEGORY: 'Category Based',
      DAY: 'Day Based',
      LOCATION: 'Location Based'
    }
    return ruleTypeLabels[ruleType] || ruleType
  }

  // Helper function to get rule type color
  const getRuleTypeColor = (ruleType: RuleType): 'primary' | 'secondary' | 'success' | 'warning' | 'info' => {
    const colorMap: Record<RuleType, 'primary' | 'secondary' | 'success' | 'warning' | 'info'> = {
      TIER: 'primary',
      SPEND: 'success',
      PRODUCT: 'info',
      CATEGORY: 'warning',
      DAY: 'secondary',
      LOCATION: 'primary'
    }
    return colorMap[ruleType] || 'primary'
  }

  // Helper function to format reward type display
  const formatRewardType = (rewardType: RewardType) => {
    const rewardTypeLabels: Record<RewardType, string> = {
      POINTS: 'Points',
      TOKENS: 'Tokens',
      REWARD: 'Reward Item'
    }
    return rewardTypeLabels[rewardType] || rewardType
  }

  // Helper function to get reward type color
  const getRewardTypeColor = (rewardType: RewardType): 'primary' | 'secondary' | 'success' => {
    const colorMap: Record<RewardType, 'primary' | 'secondary' | 'success'> = {
      POINTS: 'success',
      TOKENS: 'primary',
      REWARD: 'secondary'
    }
    return colorMap[rewardType] || 'primary'
  }

  // Helper function to format reward value
  const formatRewardValue = (rewardValue?: number, rewardType?: RewardType, rewardSubtype?: string) => {
    if (!rewardValue) return '-'

    // Format based on reward type
    switch (rewardType) {
      case 'POINTS':
        return `${rewardValue.toLocaleString()} pts`
      case 'TOKENS':
        return `${rewardValue.toLocaleString()} tokens`
      case 'REWARD':
        // For reward items, check if it's currency-based
        if (rewardSubtype === 'currency') {
          return formatCurrency(rewardValue)
        }
        return rewardValue.toString()
      default:
        return rewardValue.toString()
    }
  }

  // Helper function to format date
  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    })
  }

  return (
    <>
      <div className='space-y-6'>
        {/* Header Card */}
        <Card>
          <CardHeader
            avatar={<Avatar src={campaign?.metadata?.banner_url || ''} alt={campaign?.name} className='w-16 h-16' />}
            title={
              <div className='flex items-center gap-3'>
                <Typography variant='h4' component='h1' className='font-bold'>
                  {campaign?.name} ({campaign?.type})
                </Typography>

                <Chip
                  label={campaign?.is_active ? 'Active' : 'Inactive'}
                  color={campaign?.is_active ? 'success' : 'error'}
                  size='small'
                />
                <Chip
                  label={campaign?.show_on_app ? 'Show on App' : 'Hide on App'}
                  color={campaign?.show_on_app ? 'info' : 'error'}
                  size='small'
                />
              </div>
            }
            subheader={
              <div className='flex flex-col gap-1 mt-2'>
                <Typography variant='body2' color='textSecondary'>
                  {campaign?.start_date} - {campaign?.end_date}
                </Typography>
                <Typography variant='body2' color='textSecondary'>
                  {campaign?.description}
                </Typography>
              </div>
            }
          />
        </Card>

        {/* Campaign Rules Table */}
        <Card>
          <CardHeader
            title={
              <div className='flex items-center justify-between'>
                <div>
                  <Typography variant='h5' component='h2' className='font-semibold'>
                    Campaign Rules
                  </Typography>
                  {rules && rules.length > 0 && (
                    <Chip
                      label={`${rules.length} rule${rules.length !== 1 ? 's' : ''}`}
                      size='small'
                      variant='outlined'
                      className='mt-1'
                    />
                  )}
                </div>
                <Button
                  variant='contained'
                  startIcon={<i className='tabler-plus' />}
                  onClick={handleAddRule}
                  size='small'
                >
                  Add Rule
                </Button>
              </div>
            }
            subheader={
              <Typography variant='body2' color='textSecondary'>
                Rules and rewards configuration for this campaign
              </Typography>
            }
          />
          <Divider />
          <CardContent className='p-0'>
            {rulesLoading ? (
              <Box className='p-8 text-center'>
                <Loading />
              </Box>
            ) : rulesError ? (
              <Box className='p-8 text-center'>
                <Typography variant='body1' color='error'>
                  Failed to load campaign rules
                </Typography>
                <Typography variant='body2' color='textSecondary' className='mt-1'>
                  {rulesError.message || 'Please try refreshing the page'}
                </Typography>
              </Box>
            ) : rules && rules.length > 0 ? (
              <TableContainer component={Paper} elevation={0}>
                <Table>
                  <TableHead>
                    <TableRow>
                      <TableCell>Rule Type</TableCell>
                      <TableCell>Condition</TableCell>
                      <TableCell>Reward Type</TableCell>
                      <TableCell>Reward Value</TableCell>
                      <TableCell>Subtype</TableCell>
                      <TableCell>Created</TableCell>
                      <TableCell>Updated</TableCell>
                      <TableCell align='center' width={120}>
                        Actions
                      </TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {rules.map((rule: CampaignRule) => (
                      <TableRow key={rule.id} hover>
                        <TableCell>
                          <Chip
                            label={formatRuleType(rule.rule_type)}
                            variant='outlined'
                            size='small'
                            color={getRuleTypeColor(rule.rule_type)}
                          />
                        </TableCell>
                        <TableCell>
                          <Typography variant='body2'>{rule.condition_value || '-'}</Typography>
                        </TableCell>
                        <TableCell>
                          <Chip
                            label={formatRewardType(rule.reward_type)}
                            variant='outlined'
                            size='small'
                            color={getRewardTypeColor(rule.reward_type)}
                          />
                        </TableCell>
                        <TableCell>
                          <Typography variant='body2' className='font-medium'>
                            {formatRewardValue(rule.reward_value, rule.reward_type, rule.reward_subtype)}
                          </Typography>
                        </TableCell>
                        <TableCell>
                          {rule.reward_subtype && (
                            <Chip label={rule.reward_subtype} variant='outlined' size='small' color='default' />
                          )}
                        </TableCell>
                        <TableCell>
                          <Typography variant='caption' color='textSecondary'>
                            {formatDate(rule.created_at)}
                          </Typography>
                        </TableCell>
                        <TableCell>
                          <Typography variant='caption' color='textSecondary'>
                            {formatDate(rule.updated_at)}
                          </Typography>
                        </TableCell>
                        <TableCell align='center'>
                          <Box className='flex items-center gap-1'>
                            <Tooltip title='Edit rule'>
                              <IconButton size='small' onClick={() => handleEditRule(rule)} color='primary'>
                                <i className='tabler-edit' />
                              </IconButton>
                            </Tooltip>
                            <Tooltip title='Delete rule'>
                              <IconButton size='small' onClick={() => handleDeleteRule(rule)} color='error'>
                                <i className='tabler-trash' />
                              </IconButton>
                            </Tooltip>
                          </Box>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </TableContainer>
            ) : (
              <Box className='p-8 text-center'>
                <Typography variant='body1' color='textSecondary'>
                  No rules configured for this campaign
                </Typography>
                <Typography variant='body2' color='textSecondary' className='mt-1'>
                  Add rules to define how rewards are distributed
                </Typography>
                <Button
                  variant='outlined'
                  startIcon={<i className='tabler-plus' />}
                  onClick={handleAddRule}
                  className='mt-4'
                >
                  Add First Rule
                </Button>
              </Box>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Delete Confirmation Dialog */}
      <Dialog
        open={deleteDialogOpen}
        onClose={cancelDelete}
        aria-labelledby='delete-rule-dialog-title'
        aria-describedby='delete-rule-dialog-description'
      >
        <DialogTitle id='delete-rule-dialog-title'>Confirm Delete Rule</DialogTitle>
        <DialogContent>
          <DialogContentText id='delete-rule-dialog-description'>
            Are you sure you want to delete this rule? This action cannot be undone.
            {selectedRule && (
              <Box className='mt-3 p-3 bg-gray-50 rounded'>
                <Typography variant='body2' className='font-medium'>
                  Rule Details:
                </Typography>
                <Typography variant='caption' display='block'>
                  Type: {formatRuleType(selectedRule.rule_type)}
                </Typography>
                <Typography variant='caption' display='block'>
                  Reward:{' '}
                  {formatRewardValue(selectedRule.reward_value, selectedRule.reward_type, selectedRule.reward_subtype)}
                </Typography>
              </Box>
            )}
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={cancelDelete} color='primary'>
            Cancel
          </Button>
          <Button onClick={confirmDeleteRule} color='error' variant='contained'>
            Delete
          </Button>
        </DialogActions>
      </Dialog>
    </>
  )
}

export default CampaignDetailContent
