import { useState } from "react";
import { motion } from "motion/react";
import { 
  ArrowLeft, 
  Users, 
  Calendar, 
  Plus, 
  Crown,
  Clock,
  CheckCircle2,
  User
} from "lucide-react";
import { Button } from "./ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { Badge } from "./ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs";
import { Alert, AlertDescription } from "./ui/alert";
import { useNotifications } from "./NotificationProvider";
import { NotificationService } from "../utils/notifications";
import { formatNaira } from "../utils/currency";
import { toast } from "sonner@2.0.3";

interface GroupSavingsProps {
  onBack: () => void;
}

export function GroupSavings({ onBack }: GroupSavingsProps) {
  const [activeTab, setActiveTab] = useState("browse");
  const [showCreateForm, setShowCreateForm] = useState(false);
  const [formData, setFormData] = useState({
    name: "",
    description: "",
    targetAmount: "",
    duration: "",
    frequency: "weekly",
    maxMembers: "10"
  });
  const { showNotification } = useNotifications();

  // Mock data for existing groups
  const availableGroups = [
    {
      id: 1,
      name: "Young Professionals Circle",
      description: "Saving for investment opportunities",
      currentMembers: 8,
      maxMembers: 10,
      targetAmount: 500000,
      contribution: 25000,
      frequency: "Monthly",
      nextPayout: "2024-02-15",
      currentRound: 3,
      totalRounds: 10,
      status: "active"
    },
    {
      id: 2,
      name: "Family Goals Fund",
      description: "Building emergency funds together",
      currentMembers: 6,
      maxMembers: 8,
      targetAmount: 200000,
      contribution: 25000,
      frequency: "Weekly",
      nextPayout: "2024-01-22",
      currentRound: 1,
      totalRounds: 8,
      status: "active"
    },
    {
      id: 3,
      name: "Business Startup Pool",
      description: "Entrepreneurs saving for business capital",
      currentMembers: 12,
      maxMembers: 15,
      targetAmount: 1000000,
      contribution: 66667,
      frequency: "Monthly",
      nextPayout: "2024-03-01",
      currentRound: 5,
      totalRounds: 15,
      status: "active"
    }
  ];

  const myGroups = [
    {
      id: 1,
      name: "Young Professionals Circle",
      myPosition: 5,
      nextTurn: "4 months",
      amountSaved: 75000,
      expectedPayout: 200000,
      status: "active"
    }
  ];

  const handleCreateGroup = async () => {
    try {
      console.log("Creating group:", formData);
      
      // Show success notification
      const groupNotification = NotificationService.getGroupSavingsNotification(
        `You've successfully created "${formData.name}" group! Invite friends to join.`,
        formData.name
      );
      await showNotification(groupNotification);
      
      toast.success("Group created successfully!", {
        description: `${formData.name} is now active and ready for members to join.`
      });
      
      setShowCreateForm(false);
      setFormData({
        name: "",
        description: "",
        targetAmount: "",
        duration: "",
        frequency: "weekly",
        maxMembers: "10"
      });
      
      // Here you would typically call an API to create the group
    } catch (error) {
      console.error("Error creating group:", error);
      toast.error("Failed to create group", {
        description: "Please try again or contact support."
      });
    }
  };

  const handleJoinGroup = async (groupId: number) => {
    try {
      const group = availableGroups.find(g => g.id === groupId);
      if (!group) return;
      
      console.log("Joining group:", groupId);
      
      // Show success notification
      const joinNotification = NotificationService.getGroupSavingsNotification(
        `Welcome to "${group.name}"! Your contribution is ${formatNaira(group.contribution)} ${group.frequency.toLowerCase()}.`,
        group.name
      );
      await showNotification(joinNotification);
      
      toast.success("Successfully joined group!", {
        description: `You're now a member of ${group.name}. First contribution is due soon.`
      });
      
      // Here you would typically call an API to join the group
    } catch (error) {
      console.error("Error joining group:", error);
      toast.error("Failed to join group", {
        description: "Please try again or contact support."
      });
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-blue-100">
      {/* Header */}
      <div className="bg-white shadow-sm border-b p-4">
        <div className="flex items-center gap-3 max-w-7xl mx-auto">
          <Button variant="ghost" size="sm" onClick={onBack}>
            <ArrowLeft className="w-4 h-4" />
          </Button>
          <Users className="w-6 h-6 text-blue-600" />
          <div>
            <h1 className="text-xl font-bold">Group Savings</h1>
            <p className="text-sm text-gray-600">Join or create savings groups</p>
          </div>
        </div>
      </div>

      <div className="max-w-7xl mx-auto p-4">
        <Tabs value={activeTab} onValueChange={setActiveTab}>
          <TabsList className="grid w-full grid-cols-3">
            <TabsTrigger value="browse">Browse Groups</TabsTrigger>
            <TabsTrigger value="my-groups">My Groups</TabsTrigger>
            <TabsTrigger value="create">Create Group</TabsTrigger>
          </TabsList>

          {/* Browse Groups Tab */}
          <TabsContent value="browse" className="space-y-6">
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.6 }}
            >
              <div className="flex justify-between items-center mb-6">
                <h2 className="text-xl font-bold">Available Groups</h2>
                <Badge className="bg-blue-100 text-blue-800">
                  {availableGroups.length} groups available
                </Badge>
              </div>

              <div className="grid gap-6">
                {availableGroups.map((group, index) => (
                  <motion.div
                    key={group.id}
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ duration: 0.6, delay: index * 0.1 }}
                  >
                    <Card className="hover:shadow-lg transition-all duration-300">
                      <CardHeader>
                        <div className="flex justify-between items-start">
                          <div>
                            <CardTitle className="text-lg">{group.name}</CardTitle>
                            <p className="text-sm text-gray-600 mt-1">{group.description}</p>
                          </div>
                          <Badge variant={group.status === "active" ? "default" : "secondary"}>
                            {group.status}
                          </Badge>
                        </div>
                      </CardHeader>
                      <CardContent>
                        <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-4">
                          <div>
                            <p className="text-sm text-gray-500">Members</p>
                            <p className="font-medium">{group.currentMembers}/{group.maxMembers}</p>
                          </div>
                          <div>
                            <p className="text-sm text-gray-500">Contribution</p>
                            <p className="font-medium">{formatNaira(group.contribution)}</p>
                          </div>
                          <div>
                            <p className="text-sm text-gray-500">Frequency</p>
                            <p className="font-medium">{group.frequency}</p>
                          </div>
                          <div>
                            <p className="text-sm text-gray-500">Next Payout</p>
                            <p className="font-medium">{group.nextPayout}</p>
                          </div>
                        </div>

                        <div className="mb-4">
                          <div className="flex justify-between text-sm mb-1">
                            <span>Round Progress</span>
                            <span>{group.currentRound}/{group.totalRounds}</span>
                          </div>
                          <div className="w-full bg-gray-200 rounded-full h-2">
                            <div 
                              className="bg-blue-600 h-2 rounded-full"
                              style={{ width: `${(group.currentRound / group.totalRounds) * 100}%` }}
                            />
                          </div>
                        </div>

                        <div className="flex justify-between items-center">
                          <div>
                            <p className="text-sm text-gray-500">Target Amount</p>
                            <p className="font-bold text-lg">{formatNaira(group.targetAmount)}</p>
                          </div>
                          <Button 
                            onClick={() => handleJoinGroup(group.id)}
                            disabled={group.currentMembers >= group.maxMembers}
                            className="bg-blue-600 hover:bg-blue-700"
                          >
                            {group.currentMembers >= group.maxMembers ? "Full" : "Join Group"}
                          </Button>
                        </div>
                      </CardContent>
                    </Card>
                  </motion.div>
                ))}
              </div>
            </motion.div>
          </TabsContent>

          {/* My Groups Tab */}
          <TabsContent value="my-groups" className="space-y-6">
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.6 }}
            >
              <h2 className="text-xl font-bold mb-6">My Savings Groups</h2>

              {myGroups.length > 0 ? (
                <div className="space-y-6">
                  {myGroups.map((group, index) => (
                    <motion.div
                      key={group.id}
                      initial={{ opacity: 0, y: 20 }}
                      animate={{ opacity: 1, y: 0 }}
                      transition={{ duration: 0.6, delay: index * 0.1 }}
                    >
                      <Card className="bg-gradient-to-r from-blue-600 to-blue-700 text-white">
                        <CardHeader>
                          <div className="flex justify-between items-start">
                            <div>
                              <CardTitle className="text-white">{group.name}</CardTitle>
                              <div className="flex items-center gap-2 mt-2">
                                <Crown className="w-4 h-4" />
                                <span className="text-sm">Position #{group.myPosition}</span>
                              </div>
                            </div>
                            <Badge className="bg-white/20 text-white">
                              {group.status}
                            </Badge>
                          </div>
                        </CardHeader>
                        <CardContent>
                          <div className="grid grid-cols-2 gap-4 mb-4">
                            <div>
                              <p className="text-blue-100 text-sm">Amount Saved</p>
                              <p className="font-bold text-lg">{formatNaira(group.amountSaved)}</p>
                            </div>
                            <div>
                              <p className="text-blue-100 text-sm">Expected Payout</p>
                              <p className="font-bold text-lg">{formatNaira(group.expectedPayout)}</p>
                            </div>
                          </div>

                          <div className="bg-white/10 rounded-lg p-3">
                            <div className="flex items-center gap-2 mb-2">
                              <Clock className="w-4 h-4" />
                              <span className="text-sm">Next Turn</span>
                            </div>
                            <p className="font-medium">{group.nextTurn}</p>
                          </div>
                        </CardContent>
                      </Card>
                    </motion.div>
                  ))}
                </div>
              ) : (
                <Alert>
                  <Users className="w-4 h-4" />
                  <AlertDescription>
                    You haven't joined any groups yet. Browse available groups or create your own!
                  </AlertDescription>
                </Alert>
              )}
            </motion.div>
          </TabsContent>

          {/* Create Group Tab */}
          <TabsContent value="create" className="space-y-6">
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.6 }}
            >
              <h2 className="text-xl font-bold mb-6">Create a New Group</h2>

              <Card>
                <CardHeader>
                  <CardTitle>Group Details</CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div>
                    <Label htmlFor="groupName">Group Name</Label>
                    <Input
                      id="groupName"
                      value={formData.name}
                      onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))}
                      placeholder="Enter group name"
                    />
                  </div>

                  <div>
                    <Label htmlFor="description">Description</Label>
                    <Input
                      id="description"
                      value={formData.description}
                      onChange={(e) => setFormData(prev => ({ ...prev, description: e.target.value }))}
                      placeholder="What is this group saving for?"
                    />
                  </div>

                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <Label htmlFor="targetAmount">Target Amount</Label>
                      <Input
                        id="targetAmount"
                        type="number"
                        value={formData.targetAmount}
                        onChange={(e) => setFormData(prev => ({ ...prev, targetAmount: e.target.value }))}
                        placeholder="100000"
                      />
                    </div>
                    <div>
                      <Label htmlFor="maxMembers">Max Members</Label>
                      <select
                        id="maxMembers"
                        value={formData.maxMembers}
                        onChange={(e) => setFormData(prev => ({ ...prev, maxMembers: e.target.value }))}
                        className="w-full p-3 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                      >
                        {[...Array(11)].map((_, i) => i + 5).map(num => (
                          <option key={num} value={num}>{num} members</option>
                        ))}
                      </select>
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <Label htmlFor="frequency">Contribution Frequency</Label>
                      <select
                        id="frequency"
                        value={formData.frequency}
                        onChange={(e) => setFormData(prev => ({ ...prev, frequency: e.target.value }))}
                        className="w-full p-3 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                      >
                        <option value="weekly">Weekly</option>
                        <option value="monthly">Monthly</option>
                      </select>
                    </div>
                    <div>
                      <Label htmlFor="duration">Duration (months)</Label>
                      <Input
                        id="duration"
                        type="number"
                        value={formData.duration}
                        onChange={(e) => setFormData(prev => ({ ...prev, duration: e.target.value }))}
                        placeholder="12"
                        min="1"
                        max="24"
                      />
                    </div>
                  </div>

                  <Alert>
                    <AlertDescription>
                      Group savings work on a rotating basis. Each member contributes regularly, and takes turns receiving the total contribution amount.
                    </AlertDescription>
                  </Alert>

                  <Button 
                    onClick={handleCreateGroup}
                    className="w-full bg-blue-600 hover:bg-blue-700"
                    size="lg"
                    disabled={!formData.name || !formData.targetAmount}
                  >
                    Create Group
                  </Button>
                </CardContent>
              </Card>
            </motion.div>
          </TabsContent>
        </Tabs>
      </div>
    </div>
  );
}