import React, { useEffect, useMemo, useState, useRef } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  Box,
  TextField,
  Avatar,
  Grid,
  IconButton,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Typography,
} from '@mui/material';
import { PhotoCamera as PhotoCameraIcon, Delete as DeleteIcon } from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import type { IAgent } from '@/interfaces/database/agent';
import { useAgentOperations } from '@/hooks/agent-hooks';

export interface EditAgentDialogProps {
  open: boolean;
  agent?: IAgent;
  onClose: () => void;
  onSaved?: () => void;
}

const PERMISSION_OPTIONS = [
  { value: 'me', labelKey: 'common.onlyMe' },
  { value: 'team', labelKey: 'common.team' },
] as const;

const EditAgentDialog: React.FC<EditAgentDialogProps> = ({ open, agent, onClose, onSaved }) => {
  const { t } = useTranslation();
  const ops = useAgentOperations();

  const [title, setTitle] = useState('');
  const [avatar, setAvatar] = useState('');
  const [description, setDescription] = useState('');
  const [permission, setPermission] = useState<'me' | 'team' | 'public'>('me');
  const fileInputRef = useRef<HTMLInputElement>(null);

  const resizeImageToDataUrl = (file: File, maxDim = 256): Promise<string> => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = (e) => {
        const img = new Image();
        img.onload = () => {
          const canvas = document.createElement('canvas');
          const ctx = canvas.getContext('2d');
          if (!ctx) return reject(new Error('Canvas not supported'));
          const scale = Math.min(1, maxDim / Math.max(img.width, img.height));
          const w = Math.max(1, Math.round(img.width * scale));
          const h = Math.max(1, Math.round(img.height * scale));
          canvas.width = w;
          canvas.height = h;
          ctx.drawImage(img, 0, 0, w, h);
          // prefer jpeg for smaller size, fallback to png
          const mime = file.type === 'image/png' ? 'image/png' : 'image/jpeg';
          const dataUrl = canvas.toDataURL(mime, 0.85);
          resolve(dataUrl.replace(/\s/g, ''));
        };
        img.onerror = () => reject(new Error('Invalid image'));
        img.src = e.target?.result as string;
      };
      reader.onerror = () => reject(new Error('Read failed'));
      reader.readAsDataURL(file);
    });
  };

  const handleAvatarUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;
    try {
      if (!file.type.startsWith('image/')) {
        console.warn('Not an image file');
        return;
      }
      const dataUrl = await resizeImageToDataUrl(file, 256);
      setAvatar(dataUrl);
    } catch (err) {
      console.error('Avatar upload error:', err);
    }
  };

  const handleAvatarDelete = () => {
    setAvatar('');
  };

  const handleAvatarClick = () => {
    fileInputRef.current?.click();
  };

  useEffect(() => {
    if (open && agent) {
      setTitle(agent.title || '');
      setAvatar(agent.avatar || '');
      setDescription(agent.description || '');
      setPermission((agent.permission as any) || 'me');
    }
    if (!open) {
      // reset when closing to avoid stale state
      setTitle('');
      setAvatar('');
      setDescription('');
      setPermission('me');
    }
  }, [open, agent]);

  const canSubmit = useMemo(() => {
    return Boolean(title && title.trim().length > 0 && agent?.id);
  }, [title, agent]);

  const handleSave = async () => {
    if (!agent?.id) return;
    const res = await ops.editAgent({
      id: agent.id,
      title: title.trim(),
      avatar: avatar || undefined,
      description: description?.trim() ? description.trim() : null,
      permission,
      canvas_category: agent.canvas_category as any,
    } as any);
    if (res.success) {
      if (onSaved) onSaved();
      onClose();
    }
  };

  return (
    <Dialog open={open} onClose={onClose} fullWidth maxWidth="sm">
      <DialogTitle>{t('common.edit')}</DialogTitle>
      <DialogContent dividers>
        <Box display="flex" flexDirection="column" gap={2}>
          <Grid container spacing={2} alignItems="center">
            <Grid size={{ xs: 12 }}>
              <Box sx={{ display: 'flex', flexDirection: 'row', alignItems: 'center', gap: 2 }}>
                <Avatar
                  src={avatar}
                  sx={{ width: 96, height: 96, cursor: 'pointer' }}
                  onClick={handleAvatarClick}
                >
                  {!avatar && <PhotoCameraIcon sx={{ fontSize: 40 }} />}
                </Avatar>

                <Box sx={{ display: 'flex', gap: 1 }}>
                  <Button
                    variant="outlined"
                    size="small"
                    startIcon={<PhotoCameraIcon />}
                    onClick={handleAvatarClick}
                  >
                    {t('knowledge.uploadAvatar')}
                  </Button>
                  {avatar && (
                    <IconButton size="small" color="error" onClick={handleAvatarDelete}>
                      <DeleteIcon />
                    </IconButton>
                  )}
                </Box>

                <input
                  ref={fileInputRef}
                  type="file"
                  accept="image/*"
                  style={{ display: 'none' }}
                  onChange={handleAvatarUpload}
                />
              </Box>
            </Grid>
          </Grid>

          <TextField
            label={t('agent.forms.title')}
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            fullWidth
            required
          />

          <TextField
            label={t('agent.forms.description')}
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            fullWidth
            multiline
            minRows={3}
          />

          <FormControl fullWidth>
            <InputLabel>{t('agent.forms.permissionSettings')}</InputLabel>
            <Select
              value={permission}
              label={t('agent.forms.permissionSettings')}
              onChange={(e) => setPermission(e.target.value as any)}
            >
              {PERMISSION_OPTIONS.map((opt) => (
                <MenuItem key={opt.value} value={opt.value}>
                  {t(opt.labelKey)}
                </MenuItem>
              ))}
            </Select>
          </FormControl>
        </Box>
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose}>{t('dialog.cancel')}</Button>
        <Button
          variant="contained"
          onClick={handleSave}
          disabled={!canSubmit || ops.loading}
        >
          {t('common.confirm')}
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default EditAgentDialog;