import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { supabase } from '@/db/supabase';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Checkbox } from '@/components/ui/checkbox';
import { Label } from '@/components/ui/label';
import { Skeleton } from '@/components/ui/skeleton';
import { toast } from '@/hooks/use-toast';
import { Pencil, Check, X, DollarSign } from 'lucide-react';

interface PricingRule {
  id: string;
  rule_name: string;
  rule_value: number;
  description: string;
  updated_at: string;
}

export default function AdminPricing() {
  const queryClient = useQueryClient();
  const [editingRuleId, setEditingRuleId] = useState<string | null>(null);
  const [editValue, setEditValue] = useState<number>(0);

  // Simulator state
  const [basePrice, setBasePrice] = useState<number>(20);
  const [isAILead, setIsAILead] = useState<boolean>(false);
  const [selectedActivities, setSelectedActivities] = useState<string[]>([]);
  const [calculatedPrice, setCalculatedPrice] = useState<number | null>(null);

  // Fetch pricing rules
  const { data: pricingRules, isLoading } = useQuery({
    queryKey: ['pricing-rules'],
    queryFn: async () => {
      const { data, error } = await supabase
        .from('pricing_rules')
        .select('*')
        .order('rule_name');
      
      if (error) throw error;
      return data as PricingRule[];
    }
  });

  // Update pricing rule mutation
  const updateRuleMutation = useMutation({
    mutationFn: async ({ ruleName, newValue }: { ruleName: string; newValue: number }) => {
      const { error } = await (supabase.from('pricing_rules') as any)
        .update({ 
          rule_value: newValue, 
          updated_at: new Date().toISOString() 
        })
        .eq('rule_name', ruleName);
      
      if (error) throw error;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['pricing-rules'] });
      toast({
        title: 'Başarılı',
        description: 'Fiyat kuralı güncellendi',
      });
      setEditingRuleId(null);
    },
    onError: () => {
      toast({
        title: 'Hata',
        description: 'Fiyat kuralı güncellenirken hata oluştu',
        variant: 'destructive'
      });
    }
  });

  const handleEditClick = (rule: PricingRule) => {
    setEditingRuleId(rule.id);
    setEditValue(rule.rule_value);
  };

  const handleSaveClick = (ruleName: string) => {
    updateRuleMutation.mutate({ ruleName, newValue: editValue });
  };

  const handleCancelClick = () => {
    setEditingRuleId(null);
    setEditValue(0);
  };

  const handleActivityToggle = (activity: string) => {
    setSelectedActivities(prev => 
      prev.includes(activity) 
        ? prev.filter(a => a !== activity)
        : [...prev, activity]
    );
  };

  const handleCalculatePrice = async () => {
    try {
      const activities = selectedActivities.map(activity => ({
        type: activity,
        name: activity
      }));

      const { data, error } = await (supabase as any).rpc('calculate_lead_price', {
        p_base_price: basePrice,
        p_planned_activities: activities,
        p_trigger_source: isAILead ? 'ai_route_recommendation' : null
      });

      if (error) throw error;
      setCalculatedPrice(data);
    } catch (error) {
      toast({
        title: 'Hata',
        description: 'Fiyat hesaplanırken hata oluştu',
        variant: 'destructive'
      });
    }
  };

  if (isLoading) {
    return (
      <div className="container mx-auto px-4 py-8">
        <Skeleton className="h-12 w-[300px] mb-6" />
        <Skeleton className="h-[400px]" />
      </div>
    );
  }

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="flex items-center gap-3 mb-6">
        <div className="p-2 bg-primary/10 rounded-lg">
          <DollarSign className="h-6 w-6 text-primary" />
        </div>
        <h1 className="text-3xl font-bold">Fiyatlandırma Yönetimi</h1>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        {/* Pricing Rules Table */}
        <Card className="lg:col-span-2">
          <CardHeader>
            <CardTitle>Fiyat Kuralları</CardTitle>
          </CardHeader>
          <CardContent>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Kural Adı</TableHead>
                  <TableHead>Açıklama</TableHead>
                  <TableHead>Değer</TableHead>
                  <TableHead>Düzenle</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {pricingRules?.map((rule) => (
                  <TableRow key={rule.id}>
                    <TableCell className="font-medium">{rule.rule_name}</TableCell>
                    <TableCell className="text-sm text-muted-foreground">{rule.description}</TableCell>
                    <TableCell>
                      {editingRuleId === rule.id ? (
                        <Input
                          type="number"
                          step="0.01"
                          value={editValue}
                          onChange={(e) => setEditValue(Number(e.target.value))}
                          className="w-24"
                        />
                      ) : (
                        <span className="font-semibold">{rule.rule_value}</span>
                      )}
                    </TableCell>
                    <TableCell>
                      {editingRuleId === rule.id ? (
                        <div className="flex gap-2">
                          <Button
                            size="sm"
                            variant="ghost"
                            onClick={() => handleSaveClick(rule.rule_name)}
                          >
                            <Check className="h-4 w-4 text-green-600" />
                          </Button>
                          <Button
                            size="sm"
                            variant="ghost"
                            onClick={handleCancelClick}
                          >
                            <X className="h-4 w-4 text-red-600" />
                          </Button>
                        </div>
                      ) : (
                        <Button
                          size="sm"
                          variant="ghost"
                          onClick={() => handleEditClick(rule)}
                        >
                          <Pencil className="h-4 w-4" />
                        </Button>
                      )}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </CardContent>
        </Card>

        {/* Price Simulator */}
        <Card>
          <CardHeader>
            <CardTitle>Fiyat Simülatörü</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-6">
              <div className="space-y-2">
                <Label>Temel Fiyat (Base Price)</Label>
                <Input
                  type="number"
                  value={basePrice}
                  onChange={(e) => setBasePrice(Number(e.target.value))}
                  placeholder="20"
                />
              </div>

              <div className="flex items-center space-x-2 p-3 bg-muted/50 rounded-lg border">
                <Checkbox
                  id="ai-lead"
                  checked={isAILead}
                  onCheckedChange={(checked) => setIsAILead(checked as boolean)}
                />
                <Label htmlFor="ai-lead" className="cursor-pointer font-medium">AI Rota Önerisi (AI Lead)</Label>
              </div>

              <div className="space-y-3">
                <Label>Aktiviteler</Label>
                <div className="grid gap-2">
                  <div className="flex items-center space-x-2 p-2 hover:bg-muted rounded transition-colors">
                    <Checkbox
                      id="balloon"
                      checked={selectedActivities.includes('balloon')}
                      onCheckedChange={() => handleActivityToggle('balloon')}
                    />
                    <Label htmlFor="balloon" className="flex-1 cursor-pointer">Sıcak Hava Balonu (Balloon)</Label>
                  </div>
                  <div className="flex items-center space-x-2 p-2 hover:bg-muted rounded transition-colors">
                    <Checkbox
                      id="atv"
                      checked={selectedActivities.includes('atv')}
                      onCheckedChange={() => handleActivityToggle('atv')}
                    />
                    <Label htmlFor="atv" className="flex-1 cursor-pointer">ATV / At Binme (ATV/Horse)</Label>
                  </div>
                  <div className="flex items-center space-x-2 p-2 hover:bg-muted rounded transition-colors">
                    <Checkbox
                      id="guided-tour"
                      checked={selectedActivities.includes('guided tour')}
                      onCheckedChange={() => handleActivityToggle('guided tour')}
                    />
                    <Label htmlFor="guided-tour" className="flex-1 cursor-pointer">Rehberli Tur (Guided Tour)</Label>
                  </div>
                </div>
              </div>

              <Button className="w-full" onClick={handleCalculatePrice}>Fiyatı Hesapla</Button>

              {calculatedPrice !== null && (
                <div className="p-4 bg-primary/10 rounded-lg border border-primary/20 animate-in fade-in slide-in-from-top-2">
                  <p className="text-sm text-muted-foreground mb-1">Hesaplanan Fiyat</p>
                  <p className="text-3xl font-bold text-primary">{calculatedPrice} credits</p>
                </div>
              )}
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
