import React, { useState } from 'react';
import {
  Card,
  CardContent,
  Typography,
  Button,
  List,
  ListItem,
  ListItemText,
  IconButton,
  TextField,
  Box,
  Chip,
  Alert,
} from '@mui/material';
import AddIcon from '@mui/icons-material/Add';
import DeleteIcon from '@mui/icons-material/Delete';
import EditIcon from '@mui/icons-material/Edit';
import SaveIcon from '@mui/icons-material/Save';
import CancelIcon from '@mui/icons-material/Cancel';

interface ServicesCardProps {
  services: string[];
  onSave: (updatedServices: string[]) => void;
  serviceAreas: string[];
  onSaveServiceAreas: (updatedServiceAreas: string[]) => void;
}

const ServicesCard: React.FC<ServicesCardProps> = ({
  services,
  onSave,
  serviceAreas,
  onSaveServiceAreas,
}) => {
  const [isEditingServices, setIsEditingServices] = useState(false);
  const [newService, setNewService] = useState('');
  const [editedServices, setEditedServices] = useState<string[]>(services);
  const [serviceError, setServiceError] = useState('');

  const [isEditingServiceAreas, setIsEditingServiceAreas] = useState(false);
  const [newServiceArea, setNewServiceArea] = useState('');
  const [editedServiceAreas, setEditedServiceAreas] = useState<string[]>(serviceAreas);
  const [serviceAreaError, setServiceAreaError] = useState('');

  console.log(services);

  // Services Handlers
  const handleEditServicesToggle = () => {
    if (isEditingServices) {
      setEditedServices(services); // Revert on cancel
      setNewService('');
      setServiceError('');
    }
    setIsEditingServices(!isEditingServices);
  };

  const handleAddService = () => {
    if (newService.trim() && !editedServices.includes(newService.trim())) {
      setEditedServices((prev) => [...prev, newService.trim()]);
      setNewService('');
      setServiceError('');
    } else if (editedServices.includes(newService.trim())) {
      setServiceError('Service already exists.');
    } else {
      setServiceError('Service cannot be empty.');
    }
  };

  const handleDeleteService = (serviceToDelete: string) => {
    setEditedServices((prev) => prev.filter((s) => s !== serviceToDelete));
  };

  const handleSaveServices = () => {
    onSave(editedServices);
    setIsEditingServices(false);
  };

  // Service Areas Handlers
  const handleEditServiceAreasToggle = () => {
    if (isEditingServiceAreas) {
      setEditedServiceAreas(serviceAreas); // Revert on cancel
      setNewServiceArea('');
      setServiceAreaError('');
    }
    setIsEditingServiceAreas(!isEditingServiceAreas);
  };

  const handleAddServiceArea = () => {
    if (newServiceArea.trim() && !editedServiceAreas.includes(newServiceArea.trim())) {
      setEditedServiceAreas((prev) => [...prev, newServiceArea.trim()]);
      setNewServiceArea('');
      setServiceAreaError('');
    } else if (editedServiceAreas.includes(newServiceArea.trim())) {
      setServiceAreaError('Service area already exists.');
    } else {
      setServiceAreaError('Service area cannot be empty.');
    }
  };

  const handleDeleteServiceArea = (areaToDelete: string) => {
    setEditedServiceAreas((prev) => prev.filter((a) => a !== areaToDelete));
  };

  const handleSaveServiceAreas = () => {
    onSaveServiceAreas(editedServiceAreas);
    setIsEditingServiceAreas(false);
  };

  return (
    <Card sx={{ mt: 3, p: 2 }}>
      <CardContent>
        {/* Services Section */}
        <Box display="flex" justifyContent="space-between" alignItems="center" mb={2}>
          <Typography variant="h6">Services Provided</Typography>
          {isEditingServices ? (
            <Box>
              <IconButton color="primary" onClick={handleSaveServices}>
                <SaveIcon />
              </IconButton>
              <IconButton color="secondary" onClick={handleEditServicesToggle}>
                <CancelIcon />
              </IconButton>
            </Box>
          ) : (
            <IconButton color="primary" onClick={handleEditServicesToggle}>
              <EditIcon />
            </IconButton>
          )}
        </Box>
        {isEditingServices ? (
          <Box sx={{ mb: 2 }}>
            <TextField
              fullWidth
              label="Add New Service"
              value={newService}
              onChange={(e) => {
                setNewService(e.target.value);
                if (serviceError) setServiceError('');
              }}
              onKeyPress={(e) => {
                if (e.key === 'Enter') handleAddService();
              }}
              error={!!serviceError}
              helperText={serviceError}
            />
            <Button
              variant="outlined"
              startIcon={<AddIcon />}
              onClick={handleAddService}
              sx={{ mt: 1 }}
            >
              Add Service
            </Button>
            <Box sx={{ mt: 2, display: 'flex', flexWrap: 'wrap', gap: 1 }}>
              {editedServices.map((service, index) => (
                <Chip
                  key={index}
                  label={service}
                  onDelete={() => handleDeleteService(service)}
                  color="primary"
                  variant="outlined"
                />
              ))}
            </Box>
          </Box>
        ) : (
          <List dense>
            {services.length === 0 ? (
              <Typography variant="body2" color="textSecondary">
                No services listed.
              </Typography>
            ) : (
              services.map((service, index) => (
                <ListItem key={index}>
                  <ListItemText primary={service} />
                </ListItem>
              ))
            )}
          </List>
        )}

        {/* Service Areas Section */}
        <Box display="flex" justifyContent="space-between" alignItems="center" mt={4} mb={2}>
          <Typography variant="h6">Service Areas</Typography>
          {isEditingServiceAreas ? (
            <Box>
              <IconButton color="primary" onClick={handleSaveServiceAreas}>
                <SaveIcon />
              </IconButton>
              <IconButton color="secondary" onClick={handleEditServiceAreasToggle}>
                <CancelIcon />
              </IconButton>
            </Box>
          ) : (
            <IconButton color="primary" onClick={handleEditServiceAreasToggle}>
              <EditIcon />
            </IconButton>
          )}
        </Box>
        {isEditingServiceAreas ? (
          <Box sx={{ mb: 2 }}>
            <TextField
              fullWidth
              label="Add New Service Area (e.g., City, Zip Code, Neighborhood)"
              value={newServiceArea}
              onChange={(e) => {
                setNewServiceArea(e.target.value);
                if (serviceAreaError) setServiceAreaError('');
              }}
              onKeyPress={(e) => {
                if (e.key === 'Enter') handleAddServiceArea();
              }}
              error={!!serviceAreaError}
              helperText={serviceAreaError}
            />
            <Button
              variant="outlined"
              startIcon={<AddIcon />}
              onClick={handleAddServiceArea}
              sx={{ mt: 1 }}
            >
              Add Service Area
            </Button>
            <Box sx={{ mt: 2, display: 'flex', flexWrap: 'wrap', gap: 1 }}>
              {editedServiceAreas.map((area, index) => (
                <Chip
                  key={index}
                  label={area}
                  onDelete={() => handleDeleteServiceArea(area)}
                  color="secondary"
                  variant="outlined"
                />
              ))}
            </Box>
          </Box>
        ) : (
          <List dense>
            {serviceAreas.length === 0 ? (
              <Typography variant="body2" color="textSecondary">
                No service areas listed.
              </Typography>
            ) : (
              serviceAreas.map((area, index) => (
                <ListItem key={index}>
                  <ListItemText primary={area} />
                </ListItem>
              ))
            )}
          </List>
        )}
      </CardContent>
    </Card>
  );
};

export default ServicesCard;
