import React, { useState, useEffect } from 'react';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from './ui/dialog';
import { Button } from './ui/button';
import { Input } from './ui/input';
import { Label } from './ui/label';
import { Textarea } from './ui/textarea';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from './ui/select';
import api from '../utils/api';
import { toast } from 'sonner';
import { Calendar, Heart } from 'lucide-react';
import { Card } from './ui/card';

const PaymentActivationDialog = ({ open, onOpenChange, user, onSuccess }) => {
  const [loading, setLoading] = useState(false);
  const [plans, setPlans] = useState([]);
  const [selectedPlan, setSelectedPlan] = useState(null);
  const [useCustomPeriod, setUseCustomPeriod] = useState(false);
  const [formData, setFormData] = useState({
    plan_id: '',
    amount: '',
    payment_date: new Date().toISOString().split('T')[0], // Today's date
    payment_method: 'cash',
    custom_period_start: new Date().toISOString().split('T')[0],
    custom_period_end: '',
    notes: ''
  });

  // Fetch available plans on mount
  useEffect(() => {
    const fetchPlans = async () => {
      try {
        const response = await api.get('/admin/subscriptions/plans');
        setPlans(response.data.filter(p => p.active));
      } catch (error) {
        toast.error('Failed to fetch subscription plans');
      }
    };
    if (open) {
      fetchPlans();
    }
  }, [open]);

  // Update amount when plan changes (unless manually edited)
  useEffect(() => {
    if (selectedPlan && !formData.amount) {
      // Pre-fill with suggested price, or minimum price if suggested not set
      const suggestedAmount = (selectedPlan.suggested_price_cents || selectedPlan.minimum_price_cents || selectedPlan.price_cents) / 100;
      setFormData(prev => ({
        ...prev,
        amount: suggestedAmount.toFixed(2)
      }));
    }
  }, [selectedPlan]);

  // Calculate donation breakdown
  const getAmountBreakdown = () => {
    if (!selectedPlan || !formData.amount) return null;

    const totalCents = Math.round(parseFloat(formData.amount) * 100);
    const minimumCents = selectedPlan.minimum_price_cents || selectedPlan.price_cents || 3000;
    const donationCents = Math.max(0, totalCents - minimumCents);

    return {
      total: totalCents,
      base: minimumCents,
      donation: donationCents
    };
  };

  const formatPrice = (cents) => {
    return `$${(cents / 100).toFixed(2)}`;
  };

  const breakdown = getAmountBreakdown();

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

    // Validation
    if (!formData.plan_id) {
      toast.error('Please select a subscription plan');
      return;
    }
    if (!formData.amount || parseFloat(formData.amount) <= 0) {
      toast.error('Please enter a valid payment amount');
      return;
    }

    // Validate minimum amount
    const amountCents = Math.round(parseFloat(formData.amount) * 100);
    const minimumCents = selectedPlan.minimum_price_cents || selectedPlan.price_cents || 3000;
    if (amountCents < minimumCents) {
      toast.error(`Amount must be at least ${formatPrice(minimumCents)}`);
      return;
    }

    if (useCustomPeriod && (!formData.custom_period_start || !formData.custom_period_end)) {
      toast.error('Please specify both start and end dates for custom period');
      return;
    }

    setLoading(true);
    try {
      const payload = {
        plan_id: formData.plan_id,
        amount_cents: Math.round(parseFloat(formData.amount) * 100),
        payment_date: new Date(formData.payment_date).toISOString(),
        payment_method: formData.payment_method,
        override_plan_dates: useCustomPeriod,
        notes: formData.notes || null
      };

      if (useCustomPeriod) {
        payload.custom_period_start = new Date(formData.custom_period_start).toISOString();
        payload.custom_period_end = new Date(formData.custom_period_end).toISOString();
      }

      await api.post(`/admin/users/${user.id}/activate-payment`, payload);

      toast.success(`${user.first_name} ${user.last_name} activated successfully!`);
      onOpenChange(false);
      if (onSuccess) onSuccess();

      // Reset form
      setFormData({
        plan_id: '',
        amount: '',
        payment_date: new Date().toISOString().split('T')[0],
        payment_method: 'cash',
        custom_period_start: new Date().toISOString().split('T')[0],
        custom_period_end: '',
        notes: ''
      });
      setUseCustomPeriod(false);
      setSelectedPlan(null);
    } catch (error) {
      toast.error(error.response?.data?.detail || 'Failed to activate payment');
    } finally {
      setLoading(false);
    }
  };

  if (!user) return null;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[600px] bg-white rounded-2xl">
        <DialogHeader>
          <DialogTitle className="text-2xl font-semibold text-[#422268]" style={{ fontFamily: "'Inter', sans-serif" }}>
            Activate Manual Payment
          </DialogTitle>
          <DialogDescription className="text-[#664fa3]" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
            Record offline payment for {user.first_name} {user.last_name} ({user.email})
          </DialogDescription>
        </DialogHeader>

        <form onSubmit={handleSubmit} className="space-y-6 py-4">
          {/* Subscription Plan Selection */}
          <div className="space-y-2">
            <Label htmlFor="plan_id" className="text-[#422268] font-medium" style={{ fontFamily: "'Inter', sans-serif" }}>
              Subscription Plan
            </Label>
            <Select
              value={formData.plan_id}
              onValueChange={(value) => {
                const plan = plans.find(p => p.id === value);
                setSelectedPlan(plan);
                // Pre-fill with suggested price, or minimum price if suggested not set
                const suggestedAmount = plan ? (plan.suggested_price_cents || plan.minimum_price_cents || plan.price_cents) / 100 : '';
                setFormData({
                  ...formData,
                  plan_id: value,
                  amount: suggestedAmount ? suggestedAmount.toFixed(2) : ''
                });
              }}
            >
              <SelectTrigger className="rounded-xl border-2 border-[#ddd8eb]">
                <SelectValue placeholder="Select subscription plan" />
              </SelectTrigger>
              <SelectContent>
                {plans.map(plan => {
                  const minPrice = (plan.minimum_price_cents || plan.price_cents) / 100;
                  const sugPrice = plan.suggested_price_cents ? (plan.suggested_price_cents / 100) : null;
                  return (
                    <SelectItem key={plan.id} value={plan.id}>
                      {plan.name} - ${minPrice.toFixed(2)}{sugPrice && sugPrice > minPrice ? ` (Suggested: $${sugPrice.toFixed(2)})` : ''}/{plan.billing_cycle}
                    </SelectItem>
                  );
                })}
              </SelectContent>
            </Select>
            {selectedPlan && (
              <p className="text-xs text-[#664fa3]" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                {selectedPlan.description || `${selectedPlan.billing_cycle} subscription`}
              </p>
            )}
          </div>

          {/* Payment Amount */}
          <div className="space-y-2">
            <Label htmlFor="amount" className="text-[#422268] font-medium" style={{ fontFamily: "'Inter', sans-serif" }}>
              Payment Amount ($)
            </Label>
            <Input
              id="amount"
              type="number"
              step="0.01"
              min="0"
              placeholder="Enter amount"
              value={formData.amount}
              onChange={(e) => setFormData({...formData, amount: e.target.value})}
              className="rounded-xl border-2 border-[#ddd8eb] focus:border-[#664fa3]"
              required
            />
            {selectedPlan && (
              <p className="text-xs text-[#664fa3]" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                Minimum: {formatPrice(selectedPlan.minimum_price_cents || selectedPlan.price_cents || 3000)}
              </p>
            )}
          </div>

          {/* Breakdown Display */}
          {breakdown && breakdown.total >= breakdown.base && (
            <Card className="p-4 bg-[#f9f5ff] border border-[#DDD8EB]">
              <div className="space-y-2 text-sm" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                <div className="flex justify-between text-[#422268]">
                  <span>Membership Fee:</span>
                  <span className="font-semibold">{formatPrice(breakdown.base)}</span>
                </div>
                {breakdown.donation > 0 && (
                  <div className="flex justify-between text-[#ff9e77]">
                    <span className="flex items-center gap-1">
                      <Heart className="h-4 w-4" />
                      Additional Donation:
                    </span>
                    <span className="font-semibold">{formatPrice(breakdown.donation)}</span>
                  </div>
                )}
                <div className="flex justify-between text-[#422268] font-bold text-base pt-2 border-t border-[#DDD8EB]">
                  <span>Total:</span>
                  <span>{formatPrice(breakdown.total)}</span>
                </div>
              </div>
            </Card>
          )}

          {/* Payment Date */}
          <div className="space-y-2">
            <Label htmlFor="payment_date" className="text-[#422268] font-medium" style={{ fontFamily: "'Inter', sans-serif" }}>
              Payment Date
            </Label>
            <div className="relative">
              <Calendar className="absolute left-4 top-1/2 transform -translate-y-1/2 h-5 w-5 text-[#664fa3]" />
              <Input
                id="payment_date"
                type="date"
                value={formData.payment_date}
                onChange={(e) => setFormData({...formData, payment_date: e.target.value})}
                className="pl-12 rounded-xl border-2 border-[#ddd8eb] focus:border-[#664fa3]"
                required
              />
            </div>
          </div>

          {/* Payment Method */}
          <div className="space-y-2">
            <Label htmlFor="payment_method" className="text-[#422268] font-medium" style={{ fontFamily: "'Inter', sans-serif" }}>
              Payment Method
            </Label>
            <Select
              value={formData.payment_method}
              onValueChange={(value) => setFormData({...formData, payment_method: value})}
            >
              <SelectTrigger className="rounded-xl border-2 border-[#ddd8eb]">
                <SelectValue placeholder="Select payment method" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="cash">Cash</SelectItem>
                <SelectItem value="bank_transfer">Bank Transfer</SelectItem>
                <SelectItem value="check">Check</SelectItem>
                <SelectItem value="other">Other</SelectItem>
              </SelectContent>
            </Select>
          </div>

          {/* Subscription Period */}
          <div className="space-y-3">
            <Label className="text-[#422268] font-medium" style={{ fontFamily: "'Inter', sans-serif" }}>Subscription Period</Label>

            <div className="flex items-center gap-2">
              <input
                type="checkbox"
                id="use_custom_period"
                checked={useCustomPeriod}
                onChange={(e) => setUseCustomPeriod(e.target.checked)}
                className="rounded border-[#ddd8eb]"
              />
              <Label htmlFor="use_custom_period" className="text-sm text-[#664fa3] font-normal cursor-pointer" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                Use custom dates instead of plan's billing cycle
              </Label>
            </div>

            {useCustomPeriod ? (
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="custom_period_start" className="text-sm text-[#422268]" style={{ fontFamily: "'Inter', sans-serif" }}>
                    Start Date
                  </Label>
                  <Input
                    id="custom_period_start"
                    type="date"
                    value={formData.custom_period_start}
                    onChange={(e) => setFormData({...formData, custom_period_start: e.target.value})}
                    className="rounded-xl border-2 border-[#ddd8eb] focus:border-[#664fa3]"
                    required={useCustomPeriod}
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="custom_period_end" className="text-sm text-[#422268]" style={{ fontFamily: "'Inter', sans-serif" }}>
                    End Date
                  </Label>
                  <Input
                    id="custom_period_end"
                    type="date"
                    value={formData.custom_period_end}
                    onChange={(e) => setFormData({...formData, custom_period_end: e.target.value})}
                    className="rounded-xl border-2 border-[#ddd8eb] focus:border-[#664fa3]"
                    required={useCustomPeriod}
                  />
                </div>
              </div>
            ) : (
              selectedPlan && (
                <div className="text-sm text-[#664fa3] bg-[#f1eef9] p-3 rounded-lg space-y-2" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                  {selectedPlan.custom_cycle_enabled ? (
                    <>
                      <p>
                        <span className="font-medium text-[#422268]">Plan uses custom billing cycle:</span>
                        <br />
                        {(() => {
                          const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
                          const startMonth = months[(selectedPlan.custom_cycle_start_month || 1) - 1];
                          const endMonth = months[(selectedPlan.custom_cycle_end_month || 12) - 1];
                          return `${startMonth} ${selectedPlan.custom_cycle_start_day} - ${endMonth} ${selectedPlan.custom_cycle_end_day} (recurring annually)`;
                        })()}
                      </p>
                      <p className="text-xs">
                        Subscription will end on the upcoming cycle end date based on today's date.
                      </p>
                    </>
                  ) : (
                    <p>
                      Will use plan's billing cycle: <span className="font-medium">{selectedPlan.billing_cycle}</span>
                      <br />
                      Starts today, ends {selectedPlan.billing_cycle === 'monthly' ? '30 days' :
                        selectedPlan.billing_cycle === 'quarterly' ? '90 days' :
                        selectedPlan.billing_cycle === 'yearly' ? '1 year' :
                        selectedPlan.billing_cycle === 'lifetime' ? 'lifetime' : '1 year'} from now
                    </p>
                  )}
                </div>
              )
            )}
          </div>

          {/* Notes */}
          <div className="space-y-2">
            <Label htmlFor="notes" className="text-[#422268] font-medium" style={{ fontFamily: "'Inter', sans-serif" }}>
              Notes (Optional)
            </Label>
            <Textarea
              id="notes"
              placeholder="Additional notes about the payment..."
              value={formData.notes}
              onChange={(e) => setFormData({...formData, notes: e.target.value})}
              className="rounded-xl border-2 border-[#ddd8eb] focus:border-[#664fa3] min-h-[100px]"
            />
          </div>

          <DialogFooter className="gap-2">
            <Button
              type="button"
              variant="outline"
              onClick={() => onOpenChange(false)}
              className="rounded-full border-2 border-[#ddd8eb]"
            >
              Cancel
            </Button>
            <Button
              type="submit"
              disabled={loading}
              className="bg-[#81B29A] text-white hover:bg-[#6FA087] rounded-full"
            >
              {loading ? 'Activating...' : 'Activate Payment'}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
};

export default PaymentActivationDialog;
