/**
 * Quota Settings Page
 *
 * Manage quota overages by selecting which resources to archive.
 */

import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { useOutletContext, Link } from 'react-router-dom';
import {
  AlertTriangle, Archive, Check, ChevronDown, ChevronUp,
  Clock, Download, Users, Briefcase, Calendar, RefreshCw
} from 'lucide-react';
import { Business, User, QuotaOverage } from '../../types';
import {
  getQuotaStatus,
  getQuotaResources,
  archiveResources,
  QuotaStatus,
  QuotaResource
} from '../../api/quota';

const QuotaSettings: React.FC = () => {
  const { t } = useTranslation();
  const { business, user } = useOutletContext<{
    business: Business;
    user: User;
  }>();

  const [quotaStatus, setQuotaStatus] = useState<QuotaStatus | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [expandedOverage, setExpandedOverage] = useState<number | null>(null);
  const [resources, setResources] = useState<Record<string, QuotaResource[]>>({});
  const [selectedResources, setSelectedResources] = useState<Record<string, Set<number>>>({});
  const [archiving, setArchiving] = useState(false);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);

  const isOwner = user.role === 'owner';
  const isManager = user.role === 'manager';

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

  const loadQuotaStatus = async () => {
    try {
      setLoading(true);
      setError(null);
      const status = await getQuotaStatus();
      setQuotaStatus(status);

      // Auto-expand first overage if any
      if (status.active_overages.length > 0) {
        setExpandedOverage(status.active_overages[0].id);
        await loadResources(status.active_overages[0].quota_type);
      }
    } catch (err) {
      setError('Failed to load quota status');
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  const loadResources = async (quotaType: string) => {
    if (resources[quotaType]) return; // Already loaded

    try {
      const response = await getQuotaResources(quotaType);
      setResources(prev => ({
        ...prev,
        [quotaType]: response.resources
      }));
    } catch (err) {
      console.error('Failed to load resources:', err);
    }
  };

  const toggleOverage = async (overage: QuotaOverage) => {
    if (expandedOverage === overage.id) {
      setExpandedOverage(null);
    } else {
      setExpandedOverage(overage.id);
      await loadResources(overage.quota_type);
    }
  };

  const toggleResourceSelection = (quotaType: string, resourceId: number) => {
    setSelectedResources(prev => {
      const current = prev[quotaType] || new Set();
      const newSet = new Set(current);
      if (newSet.has(resourceId)) {
        newSet.delete(resourceId);
      } else {
        newSet.add(resourceId);
      }
      return { ...prev, [quotaType]: newSet };
    });
  };

  const handleArchive = async (quotaType: string) => {
    const selected = selectedResources[quotaType];
    if (!selected || selected.size === 0) return;

    try {
      setArchiving(true);
      const result = await archiveResources(quotaType, Array.from(selected));

      // Clear selection and reload
      setSelectedResources(prev => ({ ...prev, [quotaType]: new Set() }));
      setResources(prev => {
        const { [quotaType]: _, ...rest } = prev;
        return rest;
      });

      if (result.is_resolved) {
        setSuccessMessage(t('quota.page.resolved', 'Resolved! Your usage is now within limits.'));
        setTimeout(() => setSuccessMessage(null), 5000);
      }

      await loadQuotaStatus();
    } catch (err) {
      setError('Failed to archive resources');
      console.error(err);
    } finally {
      setArchiving(false);
    }
  };

  const getQuotaIcon = (quotaType: string) => {
    switch (quotaType) {
      case 'MAX_ADDITIONAL_USERS':
        return <Users className="h-5 w-5" />;
      case 'MAX_RESOURCES':
        return <Briefcase className="h-5 w-5" />;
      case 'MAX_SERVICES':
        return <Calendar className="h-5 w-5" />;
      default:
        return <AlertTriangle className="h-5 w-5" />;
    }
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString(undefined, {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
    });
  };

  if (!isOwner && !isManager) {
    return (
      <div className="text-center py-12">
        <p className="text-gray-500 dark:text-gray-400">
          Only business owners and managers can access quota settings.
        </p>
      </div>
    );
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <RefreshCw className="h-8 w-8 animate-spin text-brand-600" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="text-center py-12">
        <AlertTriangle className="h-12 w-12 text-red-500 mx-auto mb-4" />
        <p className="text-red-600 dark:text-red-400">{error}</p>
        <button
          onClick={loadQuotaStatus}
          className="mt-4 px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700"
        >
          {t('common.reload', 'Reload')}
        </button>
      </div>
    );
  }

  const hasOverages = quotaStatus && quotaStatus.active_overages.length > 0;

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h2 className="text-2xl font-bold text-gray-900 dark:text-white flex items-center gap-3">
          <AlertTriangle className="text-amber-500" />
          {t('quota.page.title', 'Quota Management')}
        </h2>
        <p className="text-gray-500 dark:text-gray-400 mt-1">
          {t('quota.page.subtitle', 'Manage your account limits and usage')}
        </p>
      </div>

      {/* Success Message */}
      {successMessage && (
        <div className="bg-green-50 border border-green-200 rounded-lg p-4 flex items-center gap-3">
          <Check className="h-5 w-5 text-green-600" />
          <span className="text-green-800">{successMessage}</span>
        </div>
      )}

      {/* No overages */}
      {!hasOverages && (
        <div className="bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg p-6 text-center">
          <Check className="h-12 w-12 text-green-500 mx-auto mb-4" />
          <h3 className="text-lg font-medium text-green-800 dark:text-green-200">
            {t('quota.page.noOverages', 'You are within your plan limits.')}
          </h3>
          <p className="text-green-600 dark:text-green-400 mt-2">
            All your resources are within the limits of your current plan.
          </p>
        </div>
      )}

      {/* Usage Overview */}
      {quotaStatus && (
        <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-6">
          <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-4">
            Current Usage
          </h3>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            {Object.entries(quotaStatus.usage).map(([quotaType, usage]) => {
              const isOver = usage.limit > 0 && usage.current > usage.limit;
              return (
                <div
                  key={quotaType}
                  className={`p-4 rounded-lg border ${
                    isOver
                      ? 'border-red-300 bg-red-50 dark:border-red-800 dark:bg-red-900/20'
                      : 'border-gray-200 bg-gray-50 dark:border-gray-700 dark:bg-gray-700/50'
                  }`}
                >
                  <div className="flex items-center gap-2 mb-2">
                    {getQuotaIcon(quotaType)}
                    <span className="font-medium text-gray-900 dark:text-white">
                      {usage.display_name}
                    </span>
                  </div>
                  <div className="text-2xl font-bold">
                    <span className={isOver ? 'text-red-600' : 'text-gray-900 dark:text-white'}>
                      {usage.current}
                    </span>
                    <span className="text-gray-400 text-lg">
                      {' / '}
                      {usage.limit < 0 ? 'Unlimited' : usage.limit}
                    </span>
                  </div>
                  {isOver && (
                    <p className="text-sm text-red-600 mt-1">
                      Over by {usage.current - usage.limit}
                    </p>
                  )}
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* Active Overages */}
      {hasOverages && (
        <div className="space-y-4">
          <h3 className="text-lg font-medium text-gray-900 dark:text-white">
            Active Overages
          </h3>

          {quotaStatus!.active_overages.map((overage) => (
            <div
              key={overage.id}
              className="bg-white dark:bg-gray-800 rounded-lg border border-amber-300 dark:border-amber-700 overflow-hidden"
            >
              {/* Overage Header */}
              <button
                onClick={() => toggleOverage(overage)}
                className="w-full p-4 flex items-center justify-between hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors"
              >
                <div className="flex items-center gap-4">
                  <div className={`p-2 rounded-lg ${
                    overage.days_remaining <= 1
                      ? 'bg-red-100 text-red-600'
                      : overage.days_remaining <= 7
                        ? 'bg-amber-100 text-amber-600'
                        : 'bg-amber-50 text-amber-500'
                  }`}>
                    {getQuotaIcon(overage.quota_type)}
                  </div>
                  <div className="text-left">
                    <h4 className="font-medium text-gray-900 dark:text-white">
                      {overage.display_name}
                    </h4>
                    <p className="text-sm text-gray-500">
                      {overage.current_usage} / {overage.allowed_limit}
                      {' • '}
                      <span className="text-red-600 font-medium">
                        {overage.overage_amount} over limit
                      </span>
                    </p>
                  </div>
                </div>
                <div className="flex items-center gap-4">
                  <div className={`px-3 py-1 rounded-full text-sm font-medium ${
                    overage.days_remaining <= 1
                      ? 'bg-red-100 text-red-700'
                      : overage.days_remaining <= 7
                        ? 'bg-amber-100 text-amber-700'
                        : 'bg-amber-50 text-amber-600'
                  }`}>
                    <Clock className="h-4 w-4 inline mr-1" />
                    {overage.days_remaining} days left
                  </div>
                  {expandedOverage === overage.id ? (
                    <ChevronUp className="h-5 w-5 text-gray-400" />
                  ) : (
                    <ChevronDown className="h-5 w-5 text-gray-400" />
                  )}
                </div>
              </button>

              {/* Expanded Content */}
              {expandedOverage === overage.id && (
                <div className="border-t border-gray-200 dark:border-gray-700 p-4">
                  <div className="mb-4 p-3 bg-amber-50 dark:bg-amber-900/20 rounded-lg">
                    <p className="text-sm text-amber-800 dark:text-amber-200">
                      <AlertTriangle className="h-4 w-4 inline mr-1" />
                      {t('quota.page.autoArchiveWarning',
                        'After the grace period ({{date}}), the oldest {{count}} {{type}} will be automatically archived.',
                        {
                          date: formatDate(overage.grace_period_ends_at),
                          count: overage.overage_amount,
                          type: overage.display_name
                        }
                      )}
                    </p>
                  </div>

                  <h5 className="font-medium text-gray-900 dark:text-white mb-3">
                    {t('quota.page.selectToArchive', 'Select items to archive')}
                  </h5>

                  {/* Resource List */}
                  {resources[overage.quota_type] ? (
                    <div className="space-y-2 max-h-64 overflow-y-auto">
                      {resources[overage.quota_type]
                        .filter(r => !r.is_archived)
                        .map((resource) => (
                          <label
                            key={resource.id}
                            className="flex items-center gap-3 p-3 rounded-lg border border-gray-200 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-700/50 cursor-pointer"
                          >
                            <input
                              type="checkbox"
                              checked={selectedResources[overage.quota_type]?.has(resource.id) || false}
                              onChange={() => toggleResourceSelection(overage.quota_type, resource.id)}
                              className="h-4 w-4 text-brand-600 rounded border-gray-300 focus:ring-brand-500"
                            />
                            <div className="flex-1">
                              <p className="font-medium text-gray-900 dark:text-white">
                                {resource.name}
                              </p>
                              {resource.email && (
                                <p className="text-sm text-gray-500">{resource.email}</p>
                              )}
                              {resource.role && (
                                <p className="text-sm text-gray-500">{resource.role}</p>
                              )}
                              {resource.type && (
                                <p className="text-sm text-gray-500">{resource.type}</p>
                              )}
                            </div>
                            {resource.created_at && (
                              <span className="text-xs text-gray-400">
                                Created {formatDate(resource.created_at)}
                              </span>
                            )}
                          </label>
                        ))}
                    </div>
                  ) : (
                    <div className="flex items-center justify-center py-4">
                      <RefreshCw className="h-5 w-5 animate-spin text-gray-400" />
                    </div>
                  )}

                  {/* Already Archived */}
                  {resources[overage.quota_type]?.some(r => r.is_archived) && (
                    <div className="mt-4">
                      <h6 className="text-sm font-medium text-gray-500 mb-2">Already Archived</h6>
                      <div className="space-y-2">
                        {resources[overage.quota_type]
                          .filter(r => r.is_archived)
                          .map((resource) => (
                            <div
                              key={resource.id}
                              className="flex items-center gap-3 p-3 rounded-lg bg-gray-100 dark:bg-gray-700/50"
                            >
                              <Archive className="h-4 w-4 text-gray-400" />
                              <span className="text-gray-500">{resource.name}</span>
                              {resource.archived_at && (
                                <span className="text-xs text-gray-400 ml-auto">
                                  Archived {formatDate(resource.archived_at)}
                                </span>
                              )}
                            </div>
                          ))}
                      </div>
                    </div>
                  )}

                  {/* Actions */}
                  <div className="mt-4 flex items-center gap-4 pt-4 border-t border-gray-200 dark:border-gray-700">
                    <button
                      onClick={() => handleArchive(overage.quota_type)}
                      disabled={
                        archiving ||
                        !selectedResources[overage.quota_type] ||
                        selectedResources[overage.quota_type].size === 0
                      }
                      className="flex items-center gap-2 px-4 py-2 bg-amber-600 text-white rounded-lg hover:bg-amber-700 disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      {archiving ? (
                        <RefreshCw className="h-4 w-4 animate-spin" />
                      ) : (
                        <Archive className="h-4 w-4" />
                      )}
                      {t('quota.page.archiveSelected', 'Archive Selected')}
                      {selectedResources[overage.quota_type]?.size > 0 && (
                        <span className="bg-amber-700 px-2 py-0.5 rounded-full text-xs">
                          {selectedResources[overage.quota_type].size}
                        </span>
                      )}
                    </button>
                    <Link
                      to="/dashboard/settings/billing"
                      className="flex items-center gap-2 px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700"
                    >
                      {t('quota.page.upgradeInstead', 'Upgrade Plan Instead')}
                    </Link>
                    <button className="flex items-center gap-2 px-4 py-2 text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg">
                      <Download className="h-4 w-4" />
                      {t('quota.page.exportData', 'Export Data')}
                    </button>
                  </div>

                  {/* Archive Warning */}
                  <p className="mt-3 text-sm text-gray-500">
                    <AlertTriangle className="h-4 w-4 inline mr-1" />
                    {t('quota.page.archiveWarning',
                      'Archived items will become read-only and cannot be used for new bookings.'
                    )}
                  </p>
                </div>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

export default QuotaSettings;
