import { useState } from "react";
import { useQuery, useMutation } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Plus, Edit, Trash2, FileText, Clock, CheckCircle, AlertTriangle } from "lucide-react";
import { queryClient } from "@/lib/queryClient";
import { useToast } from "@/hooks/use-toast";
import { useAuth } from "@/hooks/useAuth";
import { format } from "date-fns";

interface ClubTerms {
  id: number;
  title: string;
  content: string;
  version: string;
  type: string;
  category: string;
  isActive: boolean;
  isMandatory: boolean;
  effectiveDate: string;
  expiryDate?: string;
  minimumAge?: number;
  parentalConsent: boolean;
  digitalSignature: boolean;
  acknowledgmentText?: string;
  createdBy: string;
  createdAt: string;
  updatedAt: string;
}

interface MemberCompliance {
  hasAgreedToAll: boolean;
  pendingTerms: ClubTerms[];
  expiredAgreements: any[];
}

export default function ClubTermsPage() {
  const { user } = useAuth();
  const { toast } = useToast();
  const [selectedTerms, setSelectedTerms] = useState<ClubTerms | null>(null);
  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const [isAgreementDialogOpen, setIsAgreementDialogOpen] = useState(false);
  const [termsToAgree, setTermsToAgree] = useState<ClubTerms | null>(null);
  const [formData, setFormData] = useState({
    title: "",
    content: "",
    version: "1.0",
    type: "general",
    category: "terms",
    isActive: true,
    isMandatory: true,
    effectiveDate: new Date().toISOString().split('T')[0],
    expiryDate: "",
    minimumAge: "",
    parentalConsent: false,
    digitalSignature: false,
    acknowledgmentText: "",
  });

  const { data: allTerms = [], isLoading: isLoadingTerms } = useQuery({
    queryKey: ["/api/club-terms"],
  });

  const { data: mandatoryTerms = [], isLoading: isLoadingMandatory } = useQuery({
    queryKey: ["/api/club-terms", "mandatory"],
    queryFn: () => fetch("/api/club-terms?mandatory=true").then(res => res.json()),
  });

  const { data: compliance, isLoading: isLoadingCompliance } = useQuery({
    queryKey: ["/api/member-compliance"],
    enabled: !!user,
  });

  const createTermsMutation = useMutation({
    mutationFn: async (termsData: any) => {
      const response = await fetch("/api/club-terms", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          ...termsData,
          minimumAge: termsData.minimumAge ? parseInt(termsData.minimumAge) : null,
        }),
      });
      if (!response.ok) throw new Error("Failed to create terms");
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/club-terms"] });
      setIsCreateDialogOpen(false);
      resetForm();
      toast({
        title: "Success",
        description: "Club terms created successfully",
      });
    },
    onError: () => {
      toast({
        title: "Error",
        description: "Failed to create club terms",
        variant: "destructive",
      });
    },
  });

  const updateTermsMutation = useMutation({
    mutationFn: async ({ id, ...termsData }: any) => {
      const response = await fetch(`/api/club-terms/${id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          ...termsData,
          minimumAge: termsData.minimumAge ? parseInt(termsData.minimumAge) : null,
        }),
      });
      if (!response.ok) throw new Error("Failed to update terms");
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/club-terms"] });
      setIsEditDialogOpen(false);
      setSelectedTerms(null);
      toast({
        title: "Success",
        description: "Club terms updated successfully",
      });
    },
    onError: () => {
      toast({
        title: "Error",
        description: "Failed to update club terms",
        variant: "destructive",
      });
    },
  });

  const agreeToTermsMutation = useMutation({
    mutationFn: async (termsId: number) => {
      const response = await fetch("/api/member-terms-agreements", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ termsId }),
      });
      if (!response.ok) throw new Error("Failed to agree to terms");
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/member-compliance"] });
      setIsAgreementDialogOpen(false);
      setTermsToAgree(null);
      toast({
        title: "Success",
        description: "Agreement recorded successfully",
      });
    },
    onError: () => {
      toast({
        title: "Error",
        description: "Failed to record agreement",
        variant: "destructive",
      });
    },
  });

  const deleteTermsMutation = useMutation({
    mutationFn: async (id: number) => {
      const response = await fetch(`/api/club-terms/${id}`, {
        method: "DELETE",
      });
      if (!response.ok) throw new Error("Failed to delete terms");
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/club-terms"] });
      toast({
        title: "Success",
        description: "Club terms deleted successfully",
      });
    },
    onError: () => {
      toast({
        title: "Error",
        description: "Failed to delete club terms",
        variant: "destructive",
      });
    },
  });

  const resetForm = () => {
    setFormData({
      title: "",
      content: "",
      version: "1.0",
      type: "general",
      category: "terms",
      isActive: true,
      isMandatory: true,
      effectiveDate: new Date().toISOString().split('T')[0],
      expiryDate: "",
      minimumAge: "",
      parentalConsent: false,
      digitalSignature: false,
      acknowledgmentText: "",
    });
  };

  const openEditDialog = (terms: ClubTerms) => {
    setSelectedTerms(terms);
    setFormData({
      title: terms.title,
      content: terms.content,
      version: terms.version,
      type: terms.type,
      category: terms.category,
      isActive: terms.isActive,
      isMandatory: terms.isMandatory,
      effectiveDate: terms.effectiveDate.split('T')[0],
      expiryDate: terms.expiryDate ? terms.expiryDate.split('T')[0] : "",
      minimumAge: terms.minimumAge?.toString() || "",
      parentalConsent: terms.parentalConsent,
      digitalSignature: terms.digitalSignature,
      acknowledgmentText: terms.acknowledgmentText || "",
    });
    setIsEditDialogOpen(true);
  };

  const openAgreementDialog = (terms: ClubTerms) => {
    setTermsToAgree(terms);
    setIsAgreementDialogOpen(true);
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (selectedTerms) {
      updateTermsMutation.mutate({ id: selectedTerms.id, ...formData });
    } else {
      createTermsMutation.mutate(formData);
    }
  };

  const getTypeColor = (type: string) => {
    switch (type) {
      case "conduct": return "destructive";
      case "safety": return "orange";
      case "membership": return "blue";
      case "privacy": return "purple";
      default: return "default";
    }
  };

  const TermsCard = ({ terms, showActions = true }: { terms: ClubTerms; showActions?: boolean }) => (
    <Card className="mb-4">
      <CardHeader>
        <div className="flex justify-between items-start">
          <div className="space-y-2">
            <CardTitle className="text-lg">{terms.title}</CardTitle>
            <div className="flex gap-2">
              <Badge variant={terms.isActive ? "default" : "secondary"}>
                {terms.isActive ? "Active" : "Inactive"}
              </Badge>
              <Badge variant={getTypeColor(terms.type)}>{terms.type}</Badge>
              <Badge variant="outline">{terms.category}</Badge>
              {terms.isMandatory && <Badge variant="destructive">Mandatory</Badge>}
              <Badge variant="outline">v{terms.version}</Badge>
            </div>
          </div>
          {showActions && (
            <div className="flex gap-2">
              <Button
                size="sm"
                variant="outline"
                onClick={() => openEditDialog(terms)}
              >
                <Edit className="w-4 h-4" />
              </Button>
              <Button
                size="sm"
                variant="outline"
                onClick={() => deleteTermsMutation.mutate(terms.id)}
                disabled={deleteTermsMutation.isPending}
              >
                <Trash2 className="w-4 h-4" />
              </Button>
            </div>
          )}
        </div>
      </CardHeader>
      <CardContent>
        <div className="text-sm text-muted-foreground space-y-2">
          <div>Effective: {format(new Date(terms.effectiveDate), "MMM d, yyyy")}</div>
          {terms.expiryDate && (
            <div>Expires: {format(new Date(terms.expiryDate), "MMM d, yyyy")}</div>
          )}
          {terms.minimumAge && <div>Minimum age: {terms.minimumAge} years</div>}
          <div className="flex gap-4 mt-2">
            {terms.parentalConsent && (
              <span className="flex items-center gap-1 text-orange-600">
                <FileText className="w-3 h-3" />
                Parental consent required
              </span>
            )}
            {terms.digitalSignature && (
              <span className="flex items-center gap-1 text-blue-600">
                <FileText className="w-3 h-3" />
                Digital signature required
              </span>
            )}
          </div>
        </div>
        {!showActions && terms.isMandatory && (
          <div className="mt-4">
            <Button
              onClick={() => openAgreementDialog(terms)}
              disabled={agreeToTermsMutation.isPending}
            >
              I Agree to These Terms
            </Button>
          </div>
        )}
      </CardContent>
    </Card>
  );

  const TermsForm = () => (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div>
        <Label htmlFor="title">Title</Label>
        <Input
          id="title"
          value={formData.title}
          onChange={(e) => setFormData({ ...formData, title: e.target.value })}
          required
        />
      </div>

      <div>
        <Label htmlFor="content">Content</Label>
        <Textarea
          id="content"
          value={formData.content}
          onChange={(e) => setFormData({ ...formData, content: e.target.value })}
          rows={8}
          required
        />
      </div>

      <div className="grid grid-cols-2 gap-4">
        <div>
          <Label htmlFor="type">Type</Label>
          <Select
            value={formData.type}
            onValueChange={(value) => setFormData({ ...formData, type: value })}
          >
            <SelectTrigger>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="general">General</SelectItem>
              <SelectItem value="conduct">Code of Conduct</SelectItem>
              <SelectItem value="membership">Membership</SelectItem>
              <SelectItem value="safety">Safety</SelectItem>
              <SelectItem value="privacy">Privacy</SelectItem>
            </SelectContent>
          </Select>
        </div>

        <div>
          <Label htmlFor="category">Category</Label>
          <Select
            value={formData.category}
            onValueChange={(value) => setFormData({ ...formData, category: value })}
          >
            <SelectTrigger>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="terms">Terms & Conditions</SelectItem>
              <SelectItem value="conduct">Code of Conduct</SelectItem>
              <SelectItem value="expectations">Member Expectations</SelectItem>
              <SelectItem value="rules">Club Rules</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </div>

      <div className="grid grid-cols-3 gap-4">
        <div>
          <Label htmlFor="version">Version</Label>
          <Input
            id="version"
            value={formData.version}
            onChange={(e) => setFormData({ ...formData, version: e.target.value })}
            placeholder="1.0"
            required
          />
        </div>

        <div>
          <Label htmlFor="effectiveDate">Effective Date</Label>
          <Input
            id="effectiveDate"
            type="date"
            value={formData.effectiveDate}
            onChange={(e) => setFormData({ ...formData, effectiveDate: e.target.value })}
            required
          />
        </div>

        <div>
          <Label htmlFor="expiryDate">Expiry Date (Optional)</Label>
          <Input
            id="expiryDate"
            type="date"
            value={formData.expiryDate}
            onChange={(e) => setFormData({ ...formData, expiryDate: e.target.value })}
          />
        </div>
      </div>

      <div>
        <Label htmlFor="minimumAge">Minimum Age (Optional)</Label>
        <Input
          id="minimumAge"
          type="number"
          value={formData.minimumAge}
          onChange={(e) => setFormData({ ...formData, minimumAge: e.target.value })}
          placeholder="18"
        />
      </div>

      <div>
        <Label htmlFor="acknowledgmentText">Custom Acknowledgment Text (Optional)</Label>
        <Textarea
          id="acknowledgmentText"
          value={formData.acknowledgmentText}
          onChange={(e) => setFormData({ ...formData, acknowledgmentText: e.target.value })}
          placeholder="I acknowledge that I have read and understand..."
          rows={3}
        />
      </div>

      <div className="space-y-3">
        <div className="flex items-center space-x-2">
          <Switch
            id="isActive"
            checked={formData.isActive}
            onCheckedChange={(checked) => setFormData({ ...formData, isActive: checked })}
          />
          <Label htmlFor="isActive">Active</Label>
        </div>

        <div className="flex items-center space-x-2">
          <Switch
            id="isMandatory"
            checked={formData.isMandatory}
            onCheckedChange={(checked) => setFormData({ ...formData, isMandatory: checked })}
          />
          <Label htmlFor="isMandatory">Mandatory for all members</Label>
        </div>

        <div className="flex items-center space-x-2">
          <Switch
            id="parentalConsent"
            checked={formData.parentalConsent}
            onCheckedChange={(checked) => setFormData({ ...formData, parentalConsent: checked })}
          />
          <Label htmlFor="parentalConsent">Requires parental consent for minors</Label>
        </div>

        <div className="flex items-center space-x-2">
          <Switch
            id="digitalSignature"
            checked={formData.digitalSignature}
            onCheckedChange={(checked) => setFormData({ ...formData, digitalSignature: checked })}
          />
          <Label htmlFor="digitalSignature">Requires digital signature</Label>
        </div>
      </div>

      <div className="flex gap-2 pt-4">
        <Button type="submit" disabled={createTermsMutation.isPending || updateTermsMutation.isPending}>
          {selectedTerms ? "Update Terms" : "Create Terms"}
        </Button>
        <Button
          type="button"
          variant="outline"
          onClick={() => {
            setIsCreateDialogOpen(false);
            setIsEditDialogOpen(false);
            setSelectedTerms(null);
            resetForm();
          }}
        >
          Cancel
        </Button>
      </div>
    </form>
  );

  if (!user) {
    return (
      <div className="container mx-auto p-6">
        <div className="text-center">
          <h1 className="text-2xl font-bold mb-4">Access Denied</h1>
          <p>Please log in to view club terms.</p>
        </div>
      </div>
    );
  }

  return (
    <div className="container mx-auto p-6">
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-3xl font-bold">Club Terms & Conditions</h1>
        <Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
          <DialogTrigger asChild>
            <Button>
              <Plus className="w-4 h-4 mr-2" />
              Create Terms
            </Button>
          </DialogTrigger>
          <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle>Create Club Terms</DialogTitle>
              <DialogDescription>
                Create new terms and conditions for club members
              </DialogDescription>
            </DialogHeader>
            <TermsForm />
          </DialogContent>
        </Dialog>
      </div>

      {/* Compliance Status */}
      {compliance && !isLoadingCompliance && (
        <div className="mb-6">
          {compliance.hasAgreedToAll ? (
            <Alert>
              <CheckCircle className="h-4 w-4" />
              <AlertDescription>
                You are compliant with all mandatory club terms.
              </AlertDescription>
            </Alert>
          ) : (
            <Alert variant="destructive">
              <AlertTriangle className="h-4 w-4" />
              <AlertDescription>
                You have {compliance.pendingTerms.length} pending agreements and {compliance.expiredAgreements.length} expired agreements that require your attention.
              </AlertDescription>
            </Alert>
          )}
        </div>
      )}

      <Tabs defaultValue="compliance" className="w-full">
        <TabsList>
          <TabsTrigger value="compliance">My Compliance</TabsTrigger>
          <TabsTrigger value="mandatory">Mandatory Terms</TabsTrigger>
          <TabsTrigger value="all">All Terms</TabsTrigger>
        </TabsList>

        <TabsContent value="compliance" className="mt-6">
          {isLoadingCompliance ? (
            <div className="text-center py-8">Loading compliance status...</div>
          ) : compliance?.pendingTerms.length > 0 ? (
            <div className="space-y-4">
              <h3 className="text-lg font-semibold text-destructive">Terms Requiring Your Agreement</h3>
              {compliance.pendingTerms.map((terms: ClubTerms) => (
                <TermsCard key={terms.id} terms={terms} showActions={false} />
              ))}
            </div>
          ) : (
            <div className="text-center py-8">
              <CheckCircle className="w-12 h-12 text-green-600 mx-auto mb-4" />
              <p className="text-lg font-semibold">All Up to Date!</p>
              <p className="text-muted-foreground">You have agreed to all mandatory club terms.</p>
            </div>
          )}
        </TabsContent>

        <TabsContent value="mandatory" className="mt-6">
          {isLoadingMandatory ? (
            <div className="text-center py-8">Loading mandatory terms...</div>
          ) : mandatoryTerms.length === 0 ? (
            <div className="text-center py-8">
              <p className="text-muted-foreground">No mandatory terms found.</p>
            </div>
          ) : (
            <div className="space-y-4">
              {mandatoryTerms.map((terms: ClubTerms) => (
                <TermsCard key={terms.id} terms={terms} showActions={false} />
              ))}
            </div>
          )}
        </TabsContent>

        <TabsContent value="all" className="mt-6">
          {isLoadingTerms ? (
            <div className="text-center py-8">Loading terms...</div>
          ) : allTerms.length === 0 ? (
            <div className="text-center py-8">
              <p className="text-muted-foreground">No terms found.</p>
            </div>
          ) : (
            <div className="space-y-4">
              {allTerms.map((terms: ClubTerms) => (
                <TermsCard key={terms.id} terms={terms} />
              ))}
            </div>
          )}
        </TabsContent>
      </Tabs>

      {/* Edit Dialog */}
      <Dialog open={isEditDialogOpen} onOpenChange={setIsEditDialogOpen}>
        <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>Edit Club Terms</DialogTitle>
            <DialogDescription>
              Update the terms and conditions
            </DialogDescription>
          </DialogHeader>
          <TermsForm />
        </DialogContent>
      </Dialog>

      {/* Agreement Dialog */}
      <Dialog open={isAgreementDialogOpen} onOpenChange={setIsAgreementDialogOpen}>
        <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>Agree to Terms</DialogTitle>
            <DialogDescription>
              Please review and agree to the following terms
            </DialogDescription>
          </DialogHeader>
          {termsToAgree && (
            <div className="space-y-4">
              <div className="border rounded-lg p-4 max-h-60 overflow-y-auto">
                <h3 className="font-semibold mb-2">{termsToAgree.title}</h3>
                <div className="whitespace-pre-wrap text-sm">{termsToAgree.content}</div>
              </div>
              {termsToAgree.acknowledgmentText && (
                <div className="text-sm text-muted-foreground p-3 bg-muted rounded">
                  {termsToAgree.acknowledgmentText}
                </div>
              )}
              <div className="flex gap-2 pt-4">
                <Button
                  onClick={() => agreeToTermsMutation.mutate(termsToAgree.id)}
                  disabled={agreeToTermsMutation.isPending}
                >
                  I Agree to These Terms
                </Button>
                <Button
                  variant="outline"
                  onClick={() => {
                    setIsAgreementDialogOpen(false);
                    setTermsToAgree(null);
                  }}
                >
                  Cancel
                </Button>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}