
'use client';

import { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Check, Search, Filter, Info } from 'lucide-react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Skeleton } from '@/components/ui/skeleton';
import Image from 'next/image';

interface Material {
  id: string;
  category: string;
  name: string;
  description: string;
  basePrice: number;
  unit: string;
  brand?: string;
  color?: string;
  durability?: number;
  warranty?: number;
  imageUrl?: string;
  thumbnailUrl?: string;
  features?: string[];
  tags: string[];
  isAvailable: boolean;
  leadTime?: number;
}

interface MaterialSelectorProps {
  category: string;
  onSelect: (material: Material) => void;
  selectedMaterial?: Material;
}

export function MaterialSelector({
  category,
  onSelect,
  selectedMaterial,
}: MaterialSelectorProps) {
  const [materials, setMaterials] = useState<Material[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [filterTag, setFilterTag] = useState<string>('all');

  useEffect(() => {
    fetchMaterials();
  }, [category]);

  const fetchMaterials = async () => {
    setLoading(true);
    try {
      const response = await fetch(
        `/api/materials?category=${category}&available=true`
      );
      if (response.ok) {
        const data = await response.json();
        setMaterials(data.materials);
      }
    } catch (error) {
      console.error('Error fetching materials:', error);
    } finally {
      setLoading(false);
    }
  };

  const filteredMaterials = materials.filter((material) => {
    const matchesSearch =
      searchQuery === '' ||
      material.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      material.brand?.toLowerCase().includes(searchQuery.toLowerCase());

    const matchesFilter =
      filterTag === 'all' || material.tags.includes(filterTag);

    return matchesSearch && matchesFilter;
  });

  const allTags = Array.from(new Set(materials.flatMap((m) => m.tags)));

  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat('en-ZA', {
      style: 'currency',
      currency: 'ZAR',
      minimumFractionDigits: 0,
    }).format(amount);
  };

  if (loading) {
    return (
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {[1, 2, 3, 4, 5, 6].map((i) => (
          <Card key={i}>
            <CardContent className="p-4">
              <Skeleton className="w-full h-48 mb-4" />
              <Skeleton className="h-4 w-3/4 mb-2" />
              <Skeleton className="h-4 w-1/2" />
            </CardContent>
          </Card>
        ))}
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Search and Filter */}
      <div className="flex flex-col md:flex-row gap-4">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground" />
          <Input
            placeholder="Search materials..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="pl-10"
          />
        </div>

        <div className="flex gap-2 overflow-x-auto">
          <Button
            variant={filterTag === 'all' ? 'default' : 'outline'}
            size="sm"
            onClick={() => setFilterTag('all')}
          >
            All
          </Button>
          {allTags.map((tag) => (
            <Button
              key={tag}
              variant={filterTag === tag ? 'default' : 'outline'}
              size="sm"
              onClick={() => setFilterTag(tag)}
            >
              {tag}
            </Button>
          ))}
        </div>
      </div>

      {/* Materials Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        <AnimatePresence>
          {filteredMaterials.map((material, index) => {
            const isSelected = selectedMaterial?.id === material.id;

            return (
              <motion.div
                key={material.id}
                initial={{ opacity: 0, scale: 0.9 }}
                animate={{ opacity: 1, scale: 1 }}
                exit={{ opacity: 0, scale: 0.9 }}
                transition={{ delay: index * 0.05 }}
              >
                <Card
                  className={`cursor-pointer transition-all hover:shadow-lg ${
                    isSelected
                      ? 'ring-2 ring-primary border-primary'
                      : 'hover:border-primary/50'
                  }`}
                  onClick={() => onSelect(material)}
                >
                  {/* Material Image */}
                  <div className="relative w-full aspect-[4/3] bg-muted">
                    {material.thumbnailUrl || material.imageUrl ? (
                      <Image
                        src={material.thumbnailUrl || material.imageUrl || ''}
                        alt={material.name}
                        fill
                        className="object-cover rounded-t-lg"
                      />
                    ) : (
                      <div className="w-full h-full flex items-center justify-center text-muted-foreground">
                        <Info className="w-12 h-12" />
                      </div>
                    )}
                    
                    {isSelected && (
                      <div className="absolute top-2 right-2 w-8 h-8 rounded-full bg-primary flex items-center justify-center">
                        <Check className="w-5 h-5 text-primary-foreground" />
                      </div>
                    )}

                    {!material.isAvailable && (
                      <div className="absolute inset-0 bg-black/50 flex items-center justify-center rounded-t-lg">
                        <Badge variant="destructive">Out of Stock</Badge>
                      </div>
                    )}
                  </div>

                  <CardContent className="p-4">
                    {/* Material Info */}
                    <div className="space-y-2">
                      <div className="flex items-start justify-between">
                        <div>
                          <h4 className="font-semibold text-lg">{material.name}</h4>
                          {material.brand && (
                            <p className="text-sm text-muted-foreground">
                              {material.brand}
                            </p>
                          )}
                        </div>
                        <div className="text-right">
                          <p className="text-lg font-bold text-primary">
                            {formatCurrency(material.basePrice)}
                          </p>
                          <p className="text-xs text-muted-foreground">
                            per {material.unit}
                          </p>
                        </div>
                      </div>

                      {material.description && (
                        <p className="text-sm text-muted-foreground line-clamp-2">
                          {material.description}
                        </p>
                      )}

                      {/* Material Specs */}
                      <div className="flex flex-wrap gap-2">
                        {material.color && (
                          <Badge variant="secondary" className="text-xs">
                            {material.color}
                          </Badge>
                        )}
                        {material.warranty && (
                          <Badge variant="secondary" className="text-xs">
                            {material.warranty}yr warranty
                          </Badge>
                        )}
                        {material.durability && (
                          <Badge variant="secondary" className="text-xs">
                            {material.durability}yr life
                          </Badge>
                        )}
                      </div>

                      {/* Features */}
                      {material.features && material.features.length > 0 && (
                        <ul className="text-xs text-muted-foreground space-y-1">
                          {material.features.slice(0, 3).map((feature: string, idx: number) => (
                            <li key={idx} className="flex items-start gap-1">
                              <Check className="w-3 h-3 mt-0.5 text-green-600" />
                              <span>{feature}</span>
                            </li>
                          ))}
                        </ul>
                      )}

                      {/* Lead Time */}
                      {material.leadTime && (
                        <p className="text-xs text-muted-foreground">
                          Delivery: {material.leadTime} days
                        </p>
                      )}
                    </div>
                  </CardContent>
                </Card>
              </motion.div>
            );
          })}
        </AnimatePresence>
      </div>

      {filteredMaterials.length === 0 && (
        <Card>
          <CardContent className="p-12 text-center">
            <Filter className="w-12 h-12 mx-auto text-muted-foreground mb-4" />
            <p className="text-muted-foreground">
              No materials found matching your criteria
            </p>
          </CardContent>
        </Card>
      )}
    </div>
  );
}
