'use client';

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Shield, Layers, Infinity } from 'lucide-react';

import { limitationsApi, type TierLimits } from '@/lib/api';
import { Button } from '@/components/ui/button';
import { Switch } from '@/components/ui/switch';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { toast } from 'sonner';
import { useState, useEffect } from 'react';

interface TierLimitsFormData {
  properties_limit: string;
  tasks_limit: string;
  contractors_limit: string;
  documents_limit: string;
}

function TierLimitsCard({
  tier,
  limits,
  onSave
}: {
  tier: 'free' | 'pro';
  limits?: TierLimits;
  onSave: (tier: 'free' | 'pro', data: TierLimitsFormData) => void;
}) {
  const [formData, setFormData] = useState<TierLimitsFormData>({
    properties_limit: '',
    tasks_limit: '',
    contractors_limit: '',
    documents_limit: '',
  });

  useEffect(() => {
    if (limits) {
      setFormData({
        properties_limit: limits.properties_limit?.toString() ?? '',
        tasks_limit: limits.tasks_limit?.toString() ?? '',
        contractors_limit: limits.contractors_limit?.toString() ?? '',
        documents_limit: limits.documents_limit?.toString() ?? '',
      });
    }
  }, [limits]);

  const handleChange = (field: keyof TierLimitsFormData, value: string) => {
    // Only allow numbers or empty string
    if (value === '' || /^\d+$/.test(value)) {
      setFormData(prev => ({ ...prev, [field]: value }));
    }
  };

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2 capitalize">
          <Layers className="h-5 w-5" />
          {tier} Tier Limits
        </CardTitle>
        <CardDescription>
          {tier === 'free'
            ? 'Set resource limits for free tier users. Leave empty for unlimited.'
            : 'Set resource limits for Pro tier users. Typically left empty (unlimited).'
          }
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        <div className="grid grid-cols-2 gap-4">
          <div className="space-y-2">
            <Label htmlFor={`${tier}-properties`}>Properties Limit</Label>
            <div className="relative">
              <Input
                id={`${tier}-properties`}
                type="text"
                placeholder="Unlimited"
                value={formData.properties_limit}
                onChange={(e) => handleChange('properties_limit', e.target.value)}
              />
              {formData.properties_limit === '' && (
                <Infinity className="absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
              )}
            </div>
          </div>
          <div className="space-y-2">
            <Label htmlFor={`${tier}-tasks`}>Tasks Limit</Label>
            <div className="relative">
              <Input
                id={`${tier}-tasks`}
                type="text"
                placeholder="Unlimited"
                value={formData.tasks_limit}
                onChange={(e) => handleChange('tasks_limit', e.target.value)}
              />
              {formData.tasks_limit === '' && (
                <Infinity className="absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
              )}
            </div>
          </div>
          <div className="space-y-2">
            <Label htmlFor={`${tier}-contractors`}>Contractors Limit</Label>
            <div className="relative">
              <Input
                id={`${tier}-contractors`}
                type="text"
                placeholder="Unlimited"
                value={formData.contractors_limit}
                onChange={(e) => handleChange('contractors_limit', e.target.value)}
              />
              {formData.contractors_limit === '' && (
                <Infinity className="absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
              )}
            </div>
          </div>
          <div className="space-y-2">
            <Label htmlFor={`${tier}-documents`}>Documents Limit</Label>
            <div className="relative">
              <Input
                id={`${tier}-documents`}
                type="text"
                placeholder="Unlimited"
                value={formData.documents_limit}
                onChange={(e) => handleChange('documents_limit', e.target.value)}
              />
              {formData.documents_limit === '' && (
                <Infinity className="absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
              )}
            </div>
          </div>
        </div>
        <Button
          onClick={() => onSave(tier, formData)}
          className="w-full"
        >
          Save {tier.charAt(0).toUpperCase() + tier.slice(1)} Tier Limits
        </Button>
      </CardContent>
    </Card>
  );
}

export default function LimitationsPage() {
  const queryClient = useQueryClient();

  const { data: settings, isLoading: settingsLoading } = useQuery({
    queryKey: ['limitations-settings'],
    queryFn: limitationsApi.getSettings,
  });

  const { data: tierLimits, isLoading: limitsLoading } = useQuery({
    queryKey: ['tier-limits'],
    queryFn: limitationsApi.listTierLimits,
  });

  const updateSettingsMutation = useMutation({
    mutationFn: limitationsApi.updateSettings,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['limitations-settings'] });
      toast.success('Limitations settings updated');
    },
    onError: () => {
      toast.error('Failed to update limitations settings');
    },
  });

  const updateTierLimitsMutation = useMutation({
    mutationFn: ({ tier, data }: { tier: 'free' | 'pro'; data: TierLimitsFormData }) => {
      return limitationsApi.updateTierLimits(tier, {
        properties_limit: data.properties_limit === '' ? null : parseInt(data.properties_limit),
        tasks_limit: data.tasks_limit === '' ? null : parseInt(data.tasks_limit),
        contractors_limit: data.contractors_limit === '' ? null : parseInt(data.contractors_limit),
        documents_limit: data.documents_limit === '' ? null : parseInt(data.documents_limit),
      });
    },
    onSuccess: (_, { tier }) => {
      queryClient.invalidateQueries({ queryKey: ['tier-limits'] });
      toast.success(`${tier.charAt(0).toUpperCase() + tier.slice(1)} tier limits updated`);
    },
    onError: () => {
      toast.error('Failed to update tier limits');
    },
  });

  const handleLimitationsToggle = () => {
    if (settings) {
      updateSettingsMutation.mutate({
        enable_limitations: !settings.enable_limitations,
      });
    }
  };

  const handleSaveTierLimits = (tier: 'free' | 'pro', data: TierLimitsFormData) => {
    updateTierLimitsMutation.mutate({ tier, data });
  };

  const freeLimits = tierLimits?.find(l => l.tier === 'free');
  const proLimits = tierLimits?.find(l => l.tier === 'pro');

  if (settingsLoading || limitsLoading) {
    return (
      <div className="p-6">
        <div className="animate-pulse space-y-4">
          <div className="h-8 bg-gray-200 rounded w-1/4"></div>
          <div className="h-32 bg-gray-200 rounded"></div>
          <div className="h-64 bg-gray-200 rounded"></div>
        </div>
      </div>
    );
  }

  return (
    <div className="p-6 space-y-6">
      <div>
        <h1 className="text-2xl font-bold">Subscription Limitations</h1>
        <p className="text-muted-foreground">
          Configure tier-based resource limits for users
        </p>
      </div>

      {/* Enable Limitations Toggle */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Shield className="h-5 w-5" />
            Enable Limitations
          </CardTitle>
          <CardDescription>
            Control whether tier-based limitations are enforced for users. When disabled, all users have full access regardless of their subscription tier.
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-between">
            <div className="space-y-1">
              <Label htmlFor="enable-limitations">Enforce Tier Limitations</Label>
              <p className="text-sm text-muted-foreground">
                {settings?.enable_limitations
                  ? 'Limitations are currently ENABLED. Free tier users have restricted access.'
                  : 'Limitations are currently DISABLED. All users have full access.'
                }
              </p>
            </div>
            <Switch
              id="enable-limitations"
              checked={settings?.enable_limitations ?? false}
              onCheckedChange={handleLimitationsToggle}
              disabled={updateSettingsMutation.isPending}
            />
          </div>
        </CardContent>
      </Card>

      {/* Tier Limits */}
      <div className="grid gap-6 md:grid-cols-2">
        <TierLimitsCard
          tier="free"
          limits={freeLimits}
          onSave={handleSaveTierLimits}
        />
        <TierLimitsCard
          tier="pro"
          limits={proLimits}
          onSave={handleSaveTierLimits}
        />
      </div>

      {/* Info Box */}
      <Card className="bg-muted/50">
        <CardContent className="pt-6">
          <div className="text-sm text-muted-foreground space-y-2">
            <p><strong>How limits work:</strong></p>
            <ul className="list-disc list-inside space-y-1 ml-2">
              <li>Empty fields mean unlimited access for that resource</li>
              <li>A value of 0 means no access (blocked)</li>
              <li>Limits only apply when "Enable Limitations" is turned ON</li>
              <li>Pro tier users typically have unlimited access</li>
              <li>Changes take effect immediately for all users</li>
            </ul>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
