import { useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { FileText, Loader2 } from 'lucide-react';
import { toast } from 'sonner';

const csrfToken = () =>
  (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement | null)?.content ?? '';

const DOC_TYPES = [
  { value: 'rams', label: 'RAMS Template' },
  { value: 'method_statement', label: 'Method Statement' },
  { value: 'toolbox_talk', label: 'Toolbox Talk' },
  { value: 'permit_to_work', label: 'Permit to Work' },
  { value: 'site_induction', label: 'Site Induction Checklist' },
];

const ComplianceDocs = ({ companyId }: { companyId: string }) => {
  const [docType, setDocType] = useState('rams');
  const [topic, setTopic] = useState('');
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState<string | null>(null);

  const generate = async () => {
    if (!topic) { toast.error('Please enter a topic'); return; }
    setLoading(true);
    setResult(null);

    try {
      const docLabel = DOC_TYPES.find((d) => d.value === docType)?.label || docType;
      const res = await fetch('/api/admin/functions/ai-engineer-support', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken() },
        body: JSON.stringify({
          messages: [
            {
              role: 'user',
              content: `Generate a professional ${docLabel} document for the following topic: ${topic}. Format it as a complete, ready-to-use document with proper sections, headers, and UK compliance standards. Use markdown formatting.`,
            },
          ],
        }),
      });

      if (!res.ok) throw new Error('Failed to generate document');

      const contentType = res.headers.get('content-type') || '';
      let data: any;
      if (contentType.includes('application/json')) {
        data = await res.json();
      } else {
        data = await res.text();
      }

      // For non-streaming, read the full response
      if (typeof data === 'string') {
        setResult(data);
      } else if (data?.content) {
        setResult(data.content);
      } else {
        // Parse SSE response
        const text = typeof data === 'string' ? data : JSON.stringify(data);
        let content = '';
        for (const line of text.split('\n')) {
          if (!line.startsWith('data: ')) continue;
          const json = line.slice(6).trim();
          if (json === '[DONE]') break;
          try {
            const parsed = JSON.parse(json);
            content += parsed.choices?.[0]?.delta?.content || '';
          } catch {
            /* noop */
          }
        }
        setResult(content || 'Document generated but empty response received.');
      }

      await fetch('/api/admin/service-usage-log', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken() },
        body: JSON.stringify({
          company_id: companyId,
          service_type: 'compliance_docs',
          action: 'document_generated',
          input_data: { docType, topic },
        }),
      });
    } catch (e: any) {
      toast.error(e.message || 'Failed to generate document');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <FileText className="h-5 w-5 text-primary" /> Compliance Document Generator
          </CardTitle>
          <p className="text-sm text-muted-foreground">Generate compliance documents tailored to your operations</p>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="text-sm font-medium text-foreground">Document Type</label>
              <Select value={docType} onValueChange={setDocType}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  {DOC_TYPES.map((d) => (
                    <SelectItem key={d.value} value={d.value}>{d.label}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div>
              <label className="text-sm font-medium text-foreground">Topic / Task</label>
              <Input placeholder="e.g. Excavation near live services" value={topic} onChange={(e) => setTopic(e.target.value)} />
            </div>
          </div>
          <Button onClick={generate} disabled={loading} className="gap-2">
            {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <FileText className="h-4 w-4" />}
            {loading ? 'Generating...' : 'Generate Document'}
          </Button>
        </CardContent>
      </Card>

      {result && (
        <Card>
          <CardHeader>
            <CardTitle>Generated Document</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="prose prose-sm max-w-none text-foreground whitespace-pre-wrap">
              {result}
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  );
};

export default ComplianceDocs;
