"use client"

import { useState } from "react"
import Link from "next/link"
import { ArrowLeft, FileText, HelpCircle, AlertTriangle, CheckCircle, Loader2 } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
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, AlertTitle } from "@/components/ui/alert"
import { useWalletStore } from "@/lib/wallet-store"
import { useToast } from "@/components/ui/use-toast"

// Categories for selection
const categories = [
    "Environmental Policy",
    "Education",
    "Healthcare",
    "Infrastructure",
    "Technology",
    "Economy",
    "Social Services",
    "Other"
]

export default function ProposeIssuePage() {
    const { walletConnected } = useWalletStore()
    const { toast } = useToast()

    const [formData, setFormData] = useState({
        title: "",
        description: "",
        category: "",
        details: "",
        keywords: "",
        publicProposal: true
    })

    const [isSubmitting, setIsSubmitting] = useState(false)
    const [isSubmitted, setIsSubmitted] = useState(false)
    const [proposalId, setProposalId] = useState("")

    const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
        const { name, value } = e.target
        setFormData(prev => ({ ...prev, [name]: value }))
    }

    const handleSelectChange = (name: string) => (value: string) => {
        setFormData(prev => ({ ...prev, [name]: value }))
    }

    const handleSwitchChange = (checked: boolean) => {
        setFormData(prev => ({ ...prev, publicProposal: checked }))
    }

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault()

        if (!walletConnected) {
            toast({
                title: "Wallet not connected",
                description: "Please connect your wallet to propose a new issue.",
                variant: "destructive"
            })
            return
        }

        setIsSubmitting(true)

        try {
            // This would submit to the blockchain in production
            await new Promise(resolve => setTimeout(resolve, 2000)) // Simulate network delay

            // Generate a random ID for the demo
            const id = Math.random().toString(36).substring(2, 10)
            setProposalId(id)
            setIsSubmitted(true)
        } catch (error) {
            console.error("Error submitting proposal:", error)
            toast({
                title: "Submission failed",
                description: "There was an error submitting your proposal. Please try again.",
                variant: "destructive"
            })
        } finally {
            setIsSubmitting(false)
        }
    }

    if (isSubmitted) {
        return (
            <div className="container mx-auto px-4 py-8">
                <div className="mx-auto max-w-3xl">
                    <div className="mb-8 flex flex-col items-center text-center">
                        <CheckCircle className="h-16 w-16 text-green-500 mb-4" />
                        <h1 className="text-3xl font-bold tracking-tight sm:text-4xl">Issue Proposed Successfully!</h1>
                        <p className="mt-4 text-lg text-muted-foreground">
                            Your issue proposal has been submitted and is now pending review.
                        </p>
                        <p className="mt-2 text-sm text-muted-foreground">
                            Proposal ID: {proposalId}
                        </p>

                        <div className="mt-8 flex flex-col sm:flex-row gap-4">
                            <Button asChild variant="outline">
                                <Link href="/issues">
                                    <ArrowLeft className="mr-2 h-4 w-4" />
                                    Back to Issues
                                </Link>
                            </Button>
                            <Button onClick={() => {
                                setIsSubmitted(false)
                                setFormData({
                                    title: "",
                                    description: "",
                                    category: "",
                                    details: "",
                                    keywords: "",
                                    publicProposal: true
                                })
                            }}>
                                Propose Another Issue
                            </Button>
                        </div>
                    </div>
                </div>
            </div>
        )
    }

    return (
        <div className="container mx-auto px-4 py-8">
            <div className="mx-auto max-w-3xl">
                <Button variant="ghost" size="sm" asChild className="mb-4">
                    <Link href="/issues">
                        <ArrowLeft className="mr-2 h-4 w-4" />
                        Back to Issues
                    </Link>
                </Button>

                <div className="mb-8">
                    <h1 className="text-3xl font-bold tracking-tight sm:text-4xl">Propose a New Issue</h1>
                    <p className="mt-4 text-lg text-muted-foreground">
                        Suggest a topic for community discussion and potential policy recommendation.
                    </p>
                </div>

                {!walletConnected && (
                    <Alert variant="destructive" className="mb-6">
                        <AlertTriangle className="h-4 w-4" />
                        <AlertTitle>Wallet not connected</AlertTitle>
                        <AlertDescription>
                            You need to connect your wallet before proposing an issue.
                        </AlertDescription>
                    </Alert>
                )}

                <form onSubmit={handleSubmit}>
                    <Card>
                        <CardHeader>
                            <CardTitle>Issue Information</CardTitle>
                            <CardDescription>
                                Provide details about the issue you want to propose for discussion.
                            </CardDescription>
                        </CardHeader>
                        <CardContent className="space-y-6">
                            <div className="space-y-2">
                                <Label htmlFor="title">Issue Title</Label>
                                <Input
                                    id="title"
                                    name="title"
                                    placeholder="Enter a clear, descriptive title"
                                    value={formData.title}
                                    onChange={handleInputChange}
                                    required
                                />
                            </div>

                            <div className="space-y-2">
                                <Label htmlFor="description">Brief Description</Label>
                                <Textarea
                                    id="description"
                                    name="description"
                                    placeholder="Provide a short summary of the issue (1-2 sentences)"
                                    value={formData.description}
                                    onChange={handleInputChange}
                                    required
                                />
                                <p className="text-xs text-muted-foreground">
                                    This will appear in issue listings and search results.
                                </p>
                            </div>

                            <div className="space-y-2">
                                <Label htmlFor="category">Category</Label>
                                <Select
                                    value={formData.category}
                                    onValueChange={handleSelectChange("category")}
                                    required
                                >
                                    <SelectTrigger>
                                        <SelectValue placeholder="Select a category" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        {categories.map((category) => (
                                            <SelectItem key={category} value={category}>
                                                {category}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                            </div>

                            <div className="space-y-2">
                                <Label htmlFor="details">Detailed Description</Label>
                                <Textarea
                                    id="details"
                                    name="details"
                                    placeholder="Provide comprehensive details about the issue, including background, significance, and potential impacts"
                                    className="min-h-[200px]"
                                    value={formData.details}
                                    onChange={handleInputChange}
                                    required
                                />
                            </div>

                            <div className="space-y-2">
                                <Label htmlFor="keywords">Keywords (Optional)</Label>
                                <Input
                                    id="keywords"
                                    name="keywords"
                                    placeholder="Enter keywords separated by commas (e.g., climate, renewable, energy)"
                                    value={formData.keywords}
                                    onChange={handleInputChange}
                                />
                            </div>

                            <div className="flex items-center space-x-2">
                                <Switch
                                    id="public-proposal"
                                    checked={formData.publicProposal}
                                    onCheckedChange={handleSwitchChange}
                                />
                                <Label htmlFor="public-proposal">Make this proposal public immediately</Label>
                                <Button variant="ghost" size="icon" type="button" className="h-8 w-8">
                                    <HelpCircle className="h-4 w-4" />
                                </Button>
                            </div>
                        </CardContent>
                        <CardFooter className="border-t pt-6 flex flex-col sm:flex-row sm:justify-between gap-4">
                            <p className="text-sm text-muted-foreground">
                                All proposals are subject to community moderation
                            </p>
                            <Button type="submit" disabled={isSubmitting || !walletConnected}>
                                {isSubmitting ? (
                                    <>
                                        <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                                        Submitting...
                                    </>
                                ) : (
                                    <>
                                        <FileText className="mr-2 h-4 w-4" />
                                        Submit Proposal
                                    </>
                                )}
                            </Button>
                        </CardFooter>
                    </Card>
                </form>

                <Card className="mt-8">
                    <CardHeader>
                        <CardTitle>Proposal Guidelines</CardTitle>
                        <CardDescription>Tips for submitting an effective issue proposal</CardDescription>
                    </CardHeader>
                    <CardContent>
                        <ul className="list-disc space-y-2 pl-4 text-muted-foreground">
                            <li>Focus on issues that affect a significant portion of the community</li>
                            <li>Be clear and specific about the issue you're addressing</li>
                            <li>Provide objective information rather than personal opinions</li>
                            <li>Consider including data or research to support your proposal</li>
                            <li>Avoid duplicate issues - search first to see if your topic already exists</li>
                            <li>Maintain a constructive tone that encourages productive discussion</li>
                        </ul>
                    </CardContent>
                </Card>
            </div>
        </div>
    )
} 