
'use client';

import { useState } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import type { Business, SubscriptionPlan } from '@/lib/types';
import { CheckCircle, CreditCard, Rocket } from 'lucide-react';
import { cn } from '@/lib/utils';
import { useToast } from '@/hooks/use-toast';
import { useFirestore, useCollection, useMemoFirebase } from '@/firebase';
import { collection } from 'firebase/firestore';

interface PromoteDialogProps {
  isOpen: boolean;
  onOpenChange: (isOpen: boolean) => void;
  business: Business;
}

type PromoteStep = 'selectPlan' | 'payment' | 'confirmation';

export default function PromoteDialog({ isOpen, onOpenChange, business }: PromoteDialogProps) {
  const [step, setStep] = useState<PromoteStep>('selectPlan');
  const [selectedPlan, setSelectedPlan] = useState<SubscriptionPlan | null>(null);
  const { toast } = useToast();
  const firestore = useFirestore();

  const plansQuery = useMemoFirebase(() => firestore ? collection(firestore, 'subscriptionPlans') : null, [firestore]);
  const { data: subscriptionPlans } = useCollection<SubscriptionPlan>(plansQuery);

  const handleSelectPlan = (plan: SubscriptionPlan) => {
    setSelectedPlan(plan);
    setStep('payment');
  };

  const handlePayment = () => {
    // In a real app, this would integrate with a payment gateway
    setStep('confirmation');
  };
  
  const handleClose = () => {
    onOpenChange(false);
    // Reset state after a short delay to allow dialog to close
    setTimeout(() => {
        setStep('selectPlan');
        setSelectedPlan(null);
    }, 300);
  }

  const handleFinish = () => {
    toast({
        title: "Promotion Requested!",
        description: `Your request to promote "${business.name}" with the ${selectedPlan?.name} plan has been submitted for approval.`
    })
    handleClose();
  }


  return (
    <Dialog open={isOpen} onOpenChange={handleClose}>
      <DialogContent className="max-w-2xl">
        {step === 'selectPlan' && (
          <>
            <DialogHeader>
              <DialogTitle className="flex items-center gap-2 text-2xl">
                <Rocket className="h-6 w-6 text-accent" />
                Promote: {business.name}
              </DialogTitle>
              <DialogDescription>
                Choose a plan to feature your business on our platform. Featured businesses appear on the homepage and at the top of search results.
              </DialogDescription>
            </DialogHeader>
            <div className="grid grid-cols-1 gap-4 py-4 md:grid-cols-2">
              {subscriptionPlans?.map((plan) => (
                <Card key={plan.id} className="flex flex-col">
                  <CardHeader>
                    <CardTitle>{plan.name}</CardTitle>
                  </CardHeader>
                  <CardContent className="flex-grow space-y-4">
                    <p className="text-3xl font-bold">${plan.price.toFixed(2)}</p>
                    <p className="text-muted-foreground">{plan.durationInDays} days of promotion</p>
                    <ul className="space-y-2 text-sm">
                      <li className="flex items-center gap-2"><CheckCircle className="h-4 w-4 text-green-500" /> Featured on Homepage</li>
                      <li className="flex items-center gap-2"><CheckCircle className="h-4 w-4 text-green-500" /> Top of Search Results</li>
                      <li className="flex items-center gap-2"><CheckCircle className="h-4 w-4 text-green-500" /> Highlighted Listing</li>
                    </ul>
                  </CardContent>
                  <DialogFooter className="p-6 pt-0">
                    <Button className="w-full" onClick={() => handleSelectPlan(plan)}>Select Plan</Button>
                  </DialogFooter>
                </Card>
              ))}
            </div>
          </>
        )}

        {step === 'payment' && selectedPlan && (
          <>
            <DialogHeader>
              <DialogTitle className="text-2xl">Complete Your Purchase</DialogTitle>
              <DialogDescription>
                You are purchasing the <span className="font-bold text-primary">{selectedPlan.name}</span> plan for <span className="font-bold text-primary">${selectedPlan.price.toFixed(2)}</span>.
              </DialogDescription>
            </DialogHeader>
            <div className="py-4">
                <h3 className="mb-4 font-semibold">Payment Method</h3>
                <div className="space-y-4">
                    {/* This is a placeholder for a real payment form */}
                    <div className="rounded-md border p-4">
                        <div className="flex items-center justify-between">
                            <div className="flex items-center gap-3">
                                <CreditCard className="h-6 w-6" />
                                <div>
                                    <p className='font-medium'>Card ending in 1234</p>
                                    <p className='text-sm text-muted-foreground'>Expires 12/26</p>
                                </div>
                            </div>
                            <Button variant="outline">Change</Button>
                        </div>
                    </div>
                     <p className='text-xs text-muted-foreground'>
                        By clicking "Confirm Payment", you agree to our Terms of Service and authorize this payment. Your subscription will be submitted for admin approval upon payment.
                    </p>
                </div>
            </div>
            <DialogFooter>
              <Button variant="outline" onClick={() => setStep('selectPlan')}>Back to Plans</Button>
              <Button onClick={handlePayment}>Confirm Payment - ${selectedPlan.price.toFixed(2)}</Button>
            </DialogFooter>
          </>
        )}
        
        {step === 'confirmation' && selectedPlan && (
            <>
                <DialogHeader>
                    <DialogTitle className="text-2xl text-center">
                        <CheckCircle className="mx-auto mb-4 h-12 w-12 text-green-500" />
                        Request Submitted!
                    </DialogTitle>
                     <DialogDescription className='text-center'>
                        Your promotion request for <span className="font-bold text-primary">{business.name}</span> has been sent for approval. It will become active once an administrator reviews it.
                    </DialogDescription>
                </DialogHeader>
                <DialogFooter className="sm:justify-center">
                    <Button onClick={handleFinish}>Finish</Button>
                </DialogFooter>
            </>
        )}

      </DialogContent>
    </Dialog>
  );
}

    