/**
 * Locations Management Page
 *
 * Allows business owners/managers to manage multiple locations.
 */

import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Location } from '../types';
import {
  useLocations,
  useCreateLocation,
  useUpdateLocation,
  useDeleteLocation,
  useSetPrimaryLocation,
  useSetLocationActive,
} from '../hooks/useLocations';
import {
  Plus,
  MapPin,
  Star,
  MoreVertical,
  Edit,
  Trash2,
  Power,
  PowerOff,
  Building2,
} from 'lucide-react';
import { Modal, FormInput, Button, Alert } from '../components/ui';

interface LocationFormData {
  name: string;
  address_line1: string;
  address_line2: string;
  city: string;
  state: string;
  postal_code: string;
  country: string;
  phone: string;
  email: string;
  timezone: string;
}

const emptyFormData: LocationFormData = {
  name: '',
  address_line1: '',
  address_line2: '',
  city: '',
  state: '',
  postal_code: '',
  country: 'US',
  phone: '',
  email: '',
  timezone: '',
};

const Locations: React.FC = () => {
  const { t } = useTranslation();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingLocation, setEditingLocation] = useState<Location | null>(null);
  const [formData, setFormData] = useState<LocationFormData>(emptyFormData);
  const [activeMenu, setActiveMenu] = useState<number | null>(null);
  const [deleteConfirm, setDeleteConfirm] = useState<Location | null>(null);

  const { data: locations = [], isLoading, error } = useLocations({ includeInactive: true });
  const createMutation = useCreateLocation();
  const updateMutation = useUpdateLocation();
  const deleteMutation = useDeleteLocation();
  const setPrimaryMutation = useSetPrimaryLocation();
  const setActiveMutation = useSetLocationActive();

  const handleOpenCreate = () => {
    setEditingLocation(null);
    setFormData(emptyFormData);
    setIsModalOpen(true);
  };

  const handleOpenEdit = (location: Location) => {
    setEditingLocation(location);
    setFormData({
      name: location.name,
      address_line1: location.address_line1 || '',
      address_line2: location.address_line2 || '',
      city: location.city || '',
      state: location.state || '',
      postal_code: location.postal_code || '',
      country: location.country || 'US',
      phone: location.phone || '',
      email: location.email || '',
      timezone: location.timezone || '',
    });
    setIsModalOpen(true);
    setActiveMenu(null);
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    try {
      if (editingLocation) {
        await updateMutation.mutateAsync({
          id: editingLocation.id,
          updates: formData,
        });
      } else {
        await createMutation.mutateAsync(formData);
      }
      setIsModalOpen(false);
      setFormData(emptyFormData);
      setEditingLocation(null);
    } catch (err) {
      // Error handled by mutation
    }
  };

  const handleSetPrimary = async (location: Location) => {
    try {
      await setPrimaryMutation.mutateAsync(location.id);
      setActiveMenu(null);
    } catch (err) {
      // Error handled by mutation
    }
  };

  const handleToggleActive = async (location: Location) => {
    try {
      await setActiveMutation.mutateAsync({
        id: location.id,
        isActive: !location.is_active,
      });
      setActiveMenu(null);
    } catch (err) {
      // Error handled by mutation
    }
  };

  const handleDelete = async () => {
    if (!deleteConfirm) return;

    try {
      await deleteMutation.mutateAsync(deleteConfirm.id);
      setDeleteConfirm(null);
    } catch (err) {
      // Error handled by mutation
    }
  };

  if (isLoading) {
    return (
      <div className="p-8 max-w-7xl mx-auto">
        <div className="flex items-center justify-center py-12">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-brand-600"></div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="p-8 max-w-7xl mx-auto">
        <Alert variant="error">
          Failed to load locations: {(error as Error).message}
        </Alert>
      </div>
    );
  }

  const activeLocations = locations.filter(l => l.is_active);
  const inactiveLocations = locations.filter(l => !l.is_active);

  return (
    <div className="p-8 max-w-7xl mx-auto space-y-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <h2 className="text-2xl font-bold text-gray-900 dark:text-white">
            Locations
          </h2>
          <p className="text-gray-500 dark:text-gray-400">
            Manage your business locations
          </p>
        </div>
        <Button onClick={handleOpenCreate} variant="primary">
          <Plus size={18} />
          Add Location
        </Button>
      </div>

      {/* Mutation Errors */}
      {(createMutation.error || updateMutation.error || deleteMutation.error ||
        setPrimaryMutation.error || setActiveMutation.error) && (
        <Alert variant="error">
          {((createMutation.error || updateMutation.error || deleteMutation.error ||
            setPrimaryMutation.error || setActiveMutation.error) as any)?.response?.data?.detail ||
            'An error occurred'}
        </Alert>
      )}

      {/* Locations Grid */}
      {locations.length === 0 ? (
        <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-12 text-center">
          <Building2 className="mx-auto h-12 w-12 text-gray-400" />
          <h3 className="mt-4 text-lg font-medium text-gray-900 dark:text-white">
            No locations yet
          </h3>
          <p className="mt-2 text-gray-500 dark:text-gray-400">
            Get started by creating your first location.
          </p>
          <Button onClick={handleOpenCreate} variant="primary" className="mt-4">
            <Plus size={18} />
            Add Location
          </Button>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {/* Active Locations */}
          {activeLocations.map((location) => (
            <LocationCard
              key={location.id}
              location={location}
              isMenuOpen={activeMenu === location.id}
              onMenuToggle={() => setActiveMenu(activeMenu === location.id ? null : location.id)}
              onEdit={() => handleOpenEdit(location)}
              onSetPrimary={() => handleSetPrimary(location)}
              onToggleActive={() => handleToggleActive(location)}
              onDelete={() => setDeleteConfirm(location)}
            />
          ))}

          {/* Inactive Locations */}
          {inactiveLocations.map((location) => (
            <LocationCard
              key={location.id}
              location={location}
              isMenuOpen={activeMenu === location.id}
              onMenuToggle={() => setActiveMenu(activeMenu === location.id ? null : location.id)}
              onEdit={() => handleOpenEdit(location)}
              onSetPrimary={() => handleSetPrimary(location)}
              onToggleActive={() => handleToggleActive(location)}
              onDelete={() => setDeleteConfirm(location)}
            />
          ))}
        </div>
      )}

      {/* Add/Edit Modal */}
      <Modal
        isOpen={isModalOpen}
        onClose={() => setIsModalOpen(false)}
        title={editingLocation ? 'Edit Location' : 'Add Location'}
        size="lg"
      >
        <form onSubmit={handleSubmit} className="space-y-4">
          <FormInput
            label="Location Name"
            name="name"
            value={formData.name}
            onChange={handleInputChange}
            required
            placeholder="e.g., Main Office"
          />

          <FormInput
            label="Address Line 1"
            name="address_line1"
            value={formData.address_line1}
            onChange={handleInputChange}
            placeholder="Street address"
          />

          <FormInput
            label="Address Line 2"
            name="address_line2"
            value={formData.address_line2}
            onChange={handleInputChange}
            placeholder="Suite, unit, etc."
          />

          <div className="grid grid-cols-2 gap-4">
            <FormInput
              label="City"
              name="city"
              value={formData.city}
              onChange={handleInputChange}
            />
            <FormInput
              label="State/Province"
              name="state"
              value={formData.state}
              onChange={handleInputChange}
            />
          </div>

          <div className="grid grid-cols-2 gap-4">
            <FormInput
              label="Postal Code"
              name="postal_code"
              value={formData.postal_code}
              onChange={handleInputChange}
            />
            <FormInput
              label="Country"
              name="country"
              value={formData.country}
              onChange={handleInputChange}
            />
          </div>

          <div className="grid grid-cols-2 gap-4">
            <FormInput
              label="Phone"
              name="phone"
              type="tel"
              value={formData.phone}
              onChange={handleInputChange}
            />
            <FormInput
              label="Email"
              name="email"
              type="email"
              value={formData.email}
              onChange={handleInputChange}
            />
          </div>

          <div className="flex justify-end gap-3 pt-4">
            <Button
              type="button"
              variant="secondary"
              onClick={() => setIsModalOpen(false)}
            >
              Cancel
            </Button>
            <Button
              type="submit"
              variant="primary"
              loading={createMutation.isPending || updateMutation.isPending}
            >
              {editingLocation ? 'Save Changes' : 'Create Location'}
            </Button>
          </div>
        </form>
      </Modal>

      {/* Delete Confirmation Modal */}
      <Modal
        isOpen={!!deleteConfirm}
        onClose={() => setDeleteConfirm(null)}
        title="Delete Location"
        size="sm"
      >
        <p className="text-gray-600 dark:text-gray-400">
          Are you sure you want to delete <strong>{deleteConfirm?.name}</strong>?
          This action cannot be undone.
        </p>
        <div className="flex justify-end gap-3 mt-6">
          <Button variant="secondary" onClick={() => setDeleteConfirm(null)}>
            Cancel
          </Button>
          <Button
            variant="danger"
            onClick={handleDelete}
            loading={deleteMutation.isPending}
          >
            Delete
          </Button>
        </div>
      </Modal>
    </div>
  );
};

// Location Card Component
interface LocationCardProps {
  location: Location;
  isMenuOpen: boolean;
  onMenuToggle: () => void;
  onEdit: () => void;
  onSetPrimary: () => void;
  onToggleActive: () => void;
  onDelete: () => void;
}

const LocationCard: React.FC<LocationCardProps> = ({
  location,
  isMenuOpen,
  onMenuToggle,
  onEdit,
  onSetPrimary,
  onToggleActive,
  onDelete,
}) => {
  const address = [
    location.address_line1,
    location.city,
    location.state,
    location.postal_code,
  ].filter(Boolean).join(', ');

  return (
    <div
      className={`bg-white dark:bg-gray-800 rounded-xl border shadow-sm p-4 relative ${
        location.is_active
          ? 'border-gray-200 dark:border-gray-700'
          : 'border-gray-200 dark:border-gray-700 opacity-60'
      }`}
    >
      {/* Primary Badge */}
      {location.is_primary && (
        <div className="absolute top-2 left-2">
          <span className="inline-flex items-center gap-1 px-2 py-1 text-xs font-medium rounded-full bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400">
            <Star size={12} />
            Primary
          </span>
        </div>
      )}

      {/* Menu Button */}
      <div className="absolute top-2 right-2">
        <button
          onClick={onMenuToggle}
          className="p-1 rounded hover:bg-gray-100 dark:hover:bg-gray-700"
        >
          <MoreVertical size={18} className="text-gray-500" />
        </button>

        {/* Dropdown Menu */}
        {isMenuOpen && (
          <div className="absolute right-0 mt-1 w-48 bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-200 dark:border-gray-700 py-1 z-10">
            <button
              onClick={onEdit}
              className="flex items-center gap-2 w-full px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
            >
              <Edit size={16} />
              Edit
            </button>
            {!location.is_primary && (
              <button
                onClick={onSetPrimary}
                className="flex items-center gap-2 w-full px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
              >
                <Star size={16} />
                Set as Primary
              </button>
            )}
            <button
              onClick={onToggleActive}
              className="flex items-center gap-2 w-full px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
            >
              {location.is_active ? <PowerOff size={16} /> : <Power size={16} />}
              {location.is_active ? 'Deactivate' : 'Activate'}
            </button>
            <hr className="my-1 border-gray-200 dark:border-gray-700" />
            <button
              onClick={onDelete}
              className="flex items-center gap-2 w-full px-4 py-2 text-sm text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20"
            >
              <Trash2 size={16} />
              Delete
            </button>
          </div>
        )}
      </div>

      {/* Content */}
      <div className="pt-8">
        <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
          {location.name}
        </h3>

        {address && (
          <p className="mt-1 text-sm text-gray-500 dark:text-gray-400 flex items-start gap-1">
            <MapPin size={14} className="mt-0.5 flex-shrink-0" />
            {address}
          </p>
        )}

        {/* Stats */}
        <div className="mt-4 flex items-center gap-4 text-sm text-gray-500 dark:text-gray-400">
          {location.resource_count !== undefined && (
            <span>{location.resource_count} resources</span>
          )}
          {location.service_count !== undefined && (
            <span>{location.service_count} services</span>
          )}
        </div>

        {/* Status Badge */}
        {!location.is_active && (
          <span className="mt-3 inline-block px-2 py-1 text-xs font-medium rounded-full bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-400">
            Inactive
          </span>
        )}
      </div>
    </div>
  );
};

export default Locations;
